"""会话标题自动生成中间件 — 替代 DeerFlow TitleMiddleware"""

import logging
from ...core.llm_client import llm_client

logger = logging.getLogger(__name__)

TITLE_PROMPT = """请根据以下对话内容，生成一个简洁的中文标题（不超过{max_words}个字）。
只输出标题文本，不要加引号或其他标点。

用户消息：{user_message}
AI回复摘要：{ai_summary}"""


class TitleGenerator:
    """会话标题自动生成器"""

    def __init__(self, max_words: int = 20, max_chars: int = 50):
        self.max_words = max_words
        self.max_chars = max_chars

    def should_generate(self, state: dict) -> bool:
        """检查是否需要生成标题"""
        if state.get("title"):
            return False
        messages = state.get("messages", [])
        has_user = any(isinstance(m, dict) and m.get("role") == "user" for m in messages)
        has_ai = any(isinstance(m, dict) and m.get("role") == "assistant" for m in messages)
        return has_user and has_ai

    async def generate(self, state: dict) -> dict | None:
        """生成标题，返回 {"title": title} 或 None"""
        if not self.should_generate(state):
            return None

        messages = state.get("messages", [])
        user_msg = ""
        ai_summary = ""
        for m in messages:
            if isinstance(m, dict) and m.get("role") == "user" and not user_msg:
                user_msg = str(m.get("content", ""))
            if isinstance(m, dict) and m.get("role") == "assistant" and not ai_summary:
                ai_summary = str(m.get("content", ""))[:200]

        if not user_msg:
            return None

        # Try LLM generation
        try:
            prompt = TITLE_PROMPT.format(
                max_words=self.max_words,
                user_message=user_msg[:500],
                ai_summary=ai_summary,
            )
            title = await llm_client.chat(
                messages=[{"role": "user", "content": prompt}],
                scene_key="chat_model",
                max_tokens=64,
                temperature=0.3,
                timeout=15.0,
            )
            if title:
                title = title.strip().strip('"\'""''')
                return {"title": title[:self.max_chars]}
        except Exception as e:
            logger.warning(f"Title generation LLM failed, using fallback: {e}")

        # Fallback: first N chars of user message
        fallback = user_msg[:self.max_chars].replace("\n", " ").strip()
        if fallback:
            return {"title": fallback}
        return None
