import logging

from apipeline.pipeline.pipeline import Pipeline
from apipeline.pipeline.task import PipelineParams, PipelineTask
from apipeline.pipeline.runner import PipelineRunner
from apipeline.processors.logger import FrameLogger

from src.processors.aggregators.llm_response import (
    LLMAssistantResponseAggregator,
    LLMUserResponseAggregator,
)
from src.processors.llm.base import LLMProcessor
from src.processors.speech.tts.tts_processor import TTSProcessor
from src.modules.speech.turn_analyzer import TurnAnalyzerEnvInit
from src.common.types import AgoraParams
from src.transports.agora import AgoraTransport
from src.cmd.bots.base_agora import AgoraChannelBot
from src.cmd.bots import register_ai_room_bots
from src.types.frames.data_frames import LLMMessagesFrame
from src.types.frames.control_frames import UserStartedSpeakingFrame, UserStoppedSpeakingFrame

from dotenv import load_dotenv

load_dotenv(override=True)


@register_ai_room_bots.register
class AgoraTurnBot(AgoraChannelBot):
    """
    audio chat with agora webRTC channel voice calling bot
    """

    def __init__(self, **args) -> None:
        super().__init__(**args)
        self.init_bot_config()

    async def arun(self):
        vad_analyzer = self.get_vad_analyzer()
        turn_analyzer = TurnAnalyzerEnvInit.initTurnAnalyzerEngine(
            self._bot_config.turn.tag, self._bot_config.turn.args
        )
        params = AgoraParams(
            audio_in_enabled=True,
            audio_out_enabled=True,
            vad_enabled=True,
            vad_analyzer=vad_analyzer,
            turn_analyzer=turn_analyzer,
            vad_audio_passthrough=True,
        )

        asr_processor = self.get_asr_processor()
        llm_processor: LLMProcessor = self.get_llm_processor()
        tts_processor: TTSProcessor = self.get_tts_processor()
        stream_info = tts_processor.get_stream_info()
        params.audio_out_sample_rate = stream_info["sample_rate"]
        params.audio_out_channels = stream_info["channels"]

        transport = AgoraTransport(
            self.args.token,
            params=params,
        )

        messages = []
        if self._bot_config.llm.messages:
            messages = self._bot_config.llm.messages

        user_response = LLMUserResponseAggregator(messages)
        assistant_response = LLMAssistantResponseAggregator(messages)

        self.task = PipelineTask(
            Pipeline(
                [
                    transport.input_processor(),
                    FrameLogger(
                        include_frame_types=[UserStartedSpeakingFrame, UserStoppedSpeakingFrame]
                    ),
                    asr_processor,
                    user_response,
                    llm_processor,
                    tts_processor,
                    transport.output_processor(),
                    assistant_response,
                ]
            ),
            params=PipelineParams(
                allow_interruptions=True,
                enable_metrics=True,
                send_initial_empty_metrics=False,
            ),
        )

        transport.add_event_handlers(
            "on_first_participant_joined", [self.on_first_participant_say_hi]
        )

        await PipelineRunner().run(self.task)

    async def on_first_participant_say_hi(self, transport: AgoraTransport, user_id: int):
        # joined use tts say "hello" to introduce with llm generate
        if (
            self._bot_config.tts
            and self._bot_config.llm
            and self._bot_config.llm.messages
            and len(self._bot_config.llm.messages) == 1
        ):
            hi_text = "Please introduce yourself first."
            if self._bot_config.llm.language and self._bot_config.llm.language == "zh":
                hi_text = "请用中文介绍下自己。"
            messages = self._bot_config.llm.messages.copy()
            messages.append(
                {
                    "role": "user",
                    "content": hi_text,
                }
            )
            await self.task.queue_frames([LLMMessagesFrame(messages)])
