"""聊天服务 - 管理聊天历史和会话"""

import json
import uuid
from datetime import datetime
from pathlib import Path
from typing import List, Optional

from ..models.schemas import ChatHistoryItem, ChatMessage


class ChatService:
    """聊天服务，负责管理聊天历史"""

    def __init__(self, history_file: str = "chat_history.json", max_history: int = 50):
        self.history_file = Path(history_file)
        self.max_history = max_history
        self.current_session: List[ChatMessage] = []
        self.history: List[ChatHistoryItem] = []
        self._load_history()

    def _load_history(self):
        """加载历史记录"""
        if self.history_file.exists():
            try:
                with open(self.history_file, "r", encoding="utf-8") as f:
                    data = json.load(f)
                    self.history = [ChatHistoryItem(**item) for item in data]
            except Exception as e:
                print(f"加载历史记录失败: {e}")
                self.history = []

    def _save_history(self):
        """保存历史记录"""
        try:
            with open(self.history_file, "w", encoding="utf-8") as f:
                data = [item.model_dump(mode="json") for item in self.history]
                json.dump(data, f, ensure_ascii=False, indent=2, default=str)
        except Exception as e:
            print(f"保存历史记录失败: {e}")

    def add_message(self, role: str, content: str) -> ChatMessage:
        """添加消息到当前会话"""
        message = ChatMessage(role=role, content=content, timestamp=datetime.now())
        self.current_session.append(message)

        # 限制会话长度
        if len(self.current_session) > self.max_history:
            self.current_session = self.current_session[-self.max_history :]

        return message

    def get_current_session(self) -> List[ChatMessage]:
        """获取当前会话消息"""
        return self.current_session.copy()

    def clear_current_session(self):
        """清空当前会话"""
        if self.current_session:
            # 保存到历史记录
            history_item = ChatHistoryItem(
                id=str(uuid.uuid4()),
                messages=self.current_session.copy(),
                created_at=datetime.now(),
                updated_at=datetime.now(),
            )
            self.history.append(history_item)

            # 限制历史记录数量
            if len(self.history) > 20:
                self.history = self.history[-20:]

            self._save_history()

        self.current_session = []

    def get_history(self, limit: Optional[int] = None) -> List[ChatHistoryItem]:
        """获取历史记录"""
        if limit:
            return self.history[-limit:]
        return self.history.copy()

    def clear_history(self):
        """清空所有历史记录"""
        self.history = []
        self.current_session = []
        if self.history_file.exists():
            self.history_file.unlink()

    def build_context_messages(
        self, system_prompt: Optional[str] = None, include_history: bool = True
    ) -> List[ChatMessage]:
        """构建上下文消息（包含系统提示词和历史）"""
        messages = []

        # 添加系统提示词
        if system_prompt:
            messages.append(ChatMessage(role="system", content=system_prompt))

        # 添加历史消息
        if include_history:
            messages.extend(self.current_session)

        return messages
