"""
2.1 异常状态触发对话处理器

处理K230的异常状态（皮肤不好、情绪低落）请求
流程：拼接提示词 → LLM流式生成 → TTS流式合成 → 发送音频
"""

import asyncio
import base64
import json

from src.Module.llm.llm import StreamingLLM
from src.Module.tts.tts import StreamingTTS
from src.utils.prompts import get_trigger_prompt


async def handle_abnormal_trigger(websocket, data: dict):
    """
    处理异常状态触发对话请求

    流程：
    1. 返回确认响应
    2. 拼接提示词
    3. 流式调用LLM
    4. 流式调用TTS（从LLM生成器）
    5. 发送音频到K230

    Args:
        websocket: WebSocket连接
        data: 请求数据 {
            "type": "abnormal_trigger",
            "trigger_reason": "poor_skin" | "sad_emotion",
            "enable_streaming": true/false,
            "context_data": {...}  # optional
        }
    """
    trigger_reason = data.get("trigger_reason")
    enable_streaming = data.get("enable_streaming", True)

    # 1. 返回确认响应
    await websocket.send(json.dumps({
        "type": "abnormal_trigger_response",
        "success": True,
    }))

    if not enable_streaming:
        return

    try:
        # 2. 拼接提示词
        system_prompt = get_trigger_prompt(trigger_reason)

        # 3&4. LLM→TTS双向流（在线程池执行）
        await send_audio_stream(websocket, system_prompt)

    except Exception as e:
        print(f"[异常触发Error] {e}")
        await websocket.send(json.dumps({
            "type": "error",
            "message": str(e)
        }))


async def send_audio_stream(websocket, system_prompt: str):
    """
    在线程池中执行LLM→TTS流式处理并发送音频

    Args:
        websocket: WebSocket连接
        system_prompt: 系统提示词
    """

    def process_stream():
        """在线程池执行的同步流处理"""
        llm = StreamingLLM()
        tts = StreamingTTS(voice='Cherry')

        # 文本生成器：从LLM获取流式文本
        def text_generator():
            for chunk in llm.chat(message="", system_prompt=system_prompt):
                if chunk.error:
                    raise Exception(f"LLM Error: {chunk.error}")
                if chunk.content:
                    yield chunk.content

        # 音频生成：TTS双向流合成
        audio_chunks = []
        for audio_chunk in tts.stream_from_generator(text_generator()):
            if audio_chunk.error:
                raise Exception(f"TTS Error: {audio_chunk.error}")
            audio_chunks.append(audio_chunk)

        return audio_chunks

    # 在线程池执行
    audio_chunks = await asyncio.to_thread(process_stream)

    # 5. 发送音频到K230
    for i, audio_chunk in enumerate(audio_chunks):
        is_final = audio_chunk.is_final or (i == len(audio_chunks) - 1)
        if audio_chunk.data:
            await websocket.send(json.dumps({
                "type": "audio_stream_download",
                "session_id": "abnormal_trigger",
                "data": base64.b64encode(audio_chunk.data).decode(),
                "is_final": is_final,
            }))

    print("[2.1] 异常触发对话已完成")
