import logging

from dotenv import load_dotenv
from apipeline.pipeline.pipeline import Pipeline
from apipeline.pipeline.parallel_pipeline import ParallelPipeline
from apipeline.pipeline.task import PipelineParams, PipelineTask
from apipeline.pipeline.runner import PipelineRunner
from apipeline.processors.logger import FrameLogger
from fastapi import WebSocket

from achatbot.cmd.bots.base_fastapi_websocket_server import AIFastapiWebsocketBot
from achatbot.types.frames.data_frames import TextFrame, AudioRawFrame
from achatbot.cmd.bots import register_ai_fastapi_ws_bots
from achatbot.types.network.fastapi_websocket import FastapiWebsocketServerParams
from achatbot.transports.fastapi_websocket_server import FastapiWebsocketTransport
from achatbot.processors.punctuation_processor import PunctuationProcessor
from achatbot.modules.punctuation import PuncEnvInit
from achatbot.serializers.transcription_protobuf import TranscriptionFrameSerializer
from .helper import get_step_audio2_processor, get_step_audio2_llm


load_dotenv(override=True)

"""
TOKENIZERS_PARALLELISM=false python -m src.cmd.websocket.server.fastapi_ws_bot_serve -f config/bots/step_audio2/fastapi_websocket_STST_bot.json
"""


@register_ai_fastapi_ws_bots.register
class FastapiWebsocketServerStepAudio2STSTBot(AIFastapiWebsocketBot):
    """
    fastapi websocket input/output server bot with step2_audio(translate task)
    """

    def __init__(self, websocket: WebSocket | None = None, **args) -> None:
        super().__init__(websocket=websocket, **args)
        self.init_bot_config()

        self.vad_analyzer = None
        self.audio_llm = None

    def load(self):
        self.vad_analyzer = self.get_vad_analyzer()
        self.audio_llm = get_step_audio2_llm(self.bot_config())

        # load punctuation engine
        if self._bot_config.punctuation:
            tag = self._bot_config.punctuation.tag
            args = self._bot_config.punctuation.args or {}
            self.asr_punc_engine = PuncEnvInit.initEngine(tag, **args)

    async def arun(self):
        if self._websocket is None:
            return
        assert self.vad_analyzer is not None
        assert self.audio_llm is not None

        self.params = FastapiWebsocketServerParams(
            audio_in_enabled=True,
            audio_out_enabled=True,
            add_wav_header=True,
            vad_enabled=True,
            vad_analyzer=self.vad_analyzer,
            vad_audio_passthrough=True,
            serializer=TranscriptionFrameSerializer(),
        )
        # src/processors/voice/step_audio2_processor.py
        self._voice_processor = get_step_audio2_processor(
            bot_config=self._bot_config.voice_llm,
            session=self.session,
            audio_llm=self.audio_llm,
            processor_class_name="StepS2STProcessor",
        )
        if hasattr(self._voice_processor, "stream_info"):
            stream_info = self._voice_processor.stream_info
            self.params.audio_out_sample_rate = stream_info["sample_rate"]
            self.params.audio_out_channels = stream_info["channels"]
        logging.info(f"params: {self.params}")
        transport = FastapiWebsocketTransport(
            websocket=self._websocket,
            params=self.params,
        )

        if self._bot_config.asr:
            # src/processors/voice/step_audio2_processor.py
            asr_processor = get_step_audio2_processor(
                bot_config=self._bot_config.asr,
                session=self.session,
                audio_llm=self.audio_llm,
                processor_class_name="StepASRProcessor",
            )

            punc_processor = None
            if self.asr_punc_engine:
                punc_processor = PunctuationProcessor(
                    engine=self.asr_punc_engine, session=self.session
                )

            asr_processors = [
                asr_processor,
                FrameLogger(include_frame_types=[TextFrame]),
                punc_processor,
                FrameLogger(include_frame_types=[TextFrame]),
                transport.output_processor(),
            ]
            asr_processors = [p for p in asr_processors if p is not None]
            logging.info(f"{asr_processors=}")

        stst_processors = [
            self._voice_processor,
            FrameLogger(include_frame_types=[TextFrame, AudioRawFrame]),
            transport.output_processor(),
        ]
        stst_processors = [p for p in stst_processors if p is not None]
        logging.info(f"{stst_processors=}")

        processors = [
            transport.input_processor(),
            ParallelPipeline(
                asr_processors,
                stst_processors,
            ),
        ]
        processors = [p for p in processors if p is not None]
        logging.info(f"{processors=}")

        self.task = PipelineTask(
            Pipeline(processors=processors),
            params=PipelineParams(
                allow_interruptions=False,
                enable_metrics=True,
                send_initial_empty_metrics=False,
            ),
        )

        transport.add_event_handler("on_client_connected", self.on_client_connected)
        transport.add_event_handler("on_client_disconnected", self.on_client_disconnected)

        self.runner = PipelineRunner(handle_sigint=self._handle_sigint)
        await self.runner.run(self.task)

    async def on_client_connected(
        self,
        transport: FastapiWebsocketTransport,
        websocket: WebSocket,
    ):
        logging.info(f"on_client_connected client:{websocket.client}")
        self.session.set_client_id(client_id=f"{websocket.client.host}:{websocket.client.port}")

        llm_conf = self._bot_config.voice_llm or self._bot_config.llm
        if llm_conf and llm_conf.init_prompt:
            await self._voice_processor.say(llm_conf.init_prompt)
