"""聊天 API"""

import json
from typing import List

from fastapi import APIRouter, HTTPException, WebSocket, WebSocketDisconnect

from ..models.schemas import (
    ChatHistoryItem,
    ChatMessage,
    ChatRequest,
    ChatResponse,
    WSChatChunk,
    WSError,
)
from ..services.ai_service import AIService
from ..services.chat_service import ChatService
from ..services.config_service import ConfigService

router = APIRouter(prefix="/chat", tags=["聊天"])

# 全局服务实例
config_service: ConfigService = None
chat_service: ChatService = None
ai_service: AIService = None


def init_services(config_svc: ConfigService, chat_svc: ChatService, ai_svc: AIService):
    """初始化服务"""
    global config_service, chat_service, ai_service
    config_service = config_svc
    chat_service = chat_svc
    ai_service = ai_svc


# ============================================================================
# WebSocket 流式聊天
# ============================================================================


@router.websocket("/stream")
async def websocket_chat(websocket: WebSocket):
    """WebSocket 流式聊天端点"""
    await websocket.accept()

    try:
        while True:
            # 接收客户端消息
            data = await websocket.receive_text()
            request_data = json.loads(data)

            # 解析请求
            message = request_data.get("message", "")
            provider = request_data.get("provider")
            model = request_data.get("model")
            prompt_id = request_data.get("prompt")

            if not message:
                error = WSError(error="消息不能为空", code="EMPTY_MESSAGE")
                await websocket.send_text(error.model_dump_json())
                continue

            try:
                # 添加用户消息到历史
                chat_service.add_message("user", message)

                # 获取系统提示词
                system_prompt = None
                if prompt_id:
                    prompts = await config_service.get_prompts()
                    if prompt_id in prompts and prompts[prompt_id].enabled:
                        system_prompt = prompts[prompt_id].content
                else:
                    # 使用默认提示词
                    prompts = await config_service.get_prompts()
                    for p in prompts.values():
                        if p.default and p.enabled:
                            system_prompt = p.content
                            break

                # 构建上下文消息
                messages = chat_service.build_context_messages(
                    system_prompt=system_prompt, include_history=True
                )

                # 流式生成回复
                full_response = ""
                async for chunk in ai_service.chat_completion(
                    messages=messages, provider_id=provider, model=model, stream=True
                ):
                    full_response += chunk

                    # 发送文本块
                    ws_chunk = WSChatChunk(content=chunk, done=False)
                    await websocket.send_text(ws_chunk.model_dump_json())

                # 生成 Live2D 参数
                live2d_params = ai_service.generate_live2d_params(full_response)

                # 发送完成消息（包含 Live2D 参数）
                final_chunk = WSChatChunk(
                    content="", live2d_params=live2d_params, done=True
                )
                await websocket.send_text(final_chunk.model_dump_json())

                # 添加助手消息到历史
                chat_service.add_message("assistant", full_response)

            except Exception as e:
                error = WSError(error=str(e), code="CHAT_ERROR")
                await websocket.send_text(error.model_dump_json())

    except WebSocketDisconnect:
        print("WebSocket 连接断开")
    except Exception as e:
        print(f"WebSocket 错误: {e}")
        try:
            error = WSError(error=str(e), code="WEBSOCKET_ERROR")
            await websocket.send_text(error.model_dump_json())
        except:
            pass


# ============================================================================
# 非流式聊天
# ============================================================================


@router.post("/completions", response_model=ChatResponse, summary="非流式聊天完成")
async def chat_completion(request: ChatRequest):
    """非流式聊天完成"""
    try:
        # 添加用户消息
        chat_service.add_message("user", request.message)

        # 获取系统提示词
        system_prompt = None
        if request.prompt:
            prompts = await config_service.get_prompts()
            if request.prompt in prompts and prompts[request.prompt].enabled:
                system_prompt = prompts[request.prompt].content

        # 构建消息
        messages = request.history or chat_service.build_context_messages(
            system_prompt=system_prompt, include_history=True
        )

        # 生成回复
        response_text = ""
        async for chunk in ai_service.chat_completion(
            messages=messages, provider_id=request.provider, model=request.model, stream=False
        ):
            response_text += chunk

        # 生成 Live2D 参数
        live2d_params = ai_service.generate_live2d_params(response_text)

        # 添加助手消息
        chat_service.add_message("assistant", response_text)

        # 获取使用的供应商和模型
        provider_id, provider = ai_service.get_provider(request.provider)
        model_name = request.model or provider.default_model

        return ChatResponse(
            message=response_text,
            provider=provider_id,
            model=model_name,
            live2d_params=live2d_params,
        )

    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))


# ============================================================================
# 聊天历史
# ============================================================================


@router.get("/history", response_model=List[ChatHistoryItem], summary="获取聊天历史")
async def get_chat_history(limit: int = 20):
    """获取聊天历史记录"""
    return chat_service.get_history(limit=limit)


@router.delete("/history", summary="清空聊天历史")
async def clear_chat_history():
    """清空所有聊天历史"""
    chat_service.clear_history()
    return {"message": "聊天历史已清空"}


@router.get("/session", response_model=List[ChatMessage], summary="获取当前会话")
async def get_current_session():
    """获取当前会话的消息"""
    return chat_service.get_current_session()


@router.delete("/session", summary="清空当前会话")
async def clear_current_session():
    """清空当前会话（会保存到历史记录）"""
    chat_service.clear_current_session()
    return {"message": "当前会话已清空"}
