"""对话摘要压缩中间件 — 替代 DeerFlow SummarizationMiddleware"""

import logging
from openai import OpenAI
from app.agent.messages import HumanMessage, AIMessage, SystemMessage, ToolMessage

logger = logging.getLogger(__name__)

SUMMARIZE_PROMPT = """请将以下执法对话历史压缩为简洁摘要，保留关键信息：
- 法律条款引用和适用依据
- 案件事实和关键细节
- 已作出的分析和结论
- 待解决的问题

对话历史：
{conversation}

请输出结构化摘要："""


class ConversationSummarizer:
    """对话摘要压缩器 — 当消息过长时自动压缩历史"""

    trigger = {"type": "messages", "value": 30}
    keep = {"type": "messages", "value": 10}

    def __init__(self, llm_base_url: str, model: str, api_key: str = ""):
        self._client = OpenAI(base_url=llm_base_url, api_key=api_key)
        self._model = model

    def _should_summarize(self, messages: list) -> bool:
        """检查是否需要摘要压缩"""
        return len(messages) >= self.trigger["value"]

    def _format_for_summary(self, messages: list) -> str:
        """格式化消息用于摘要"""
        lines = []
        for m in messages:
            if isinstance(m, HumanMessage):
                lines.append(f"用户：{str(m.content)[:300]}")
            elif isinstance(m, AIMessage):
                content = str(m.content)[:300]
                if m.tool_calls:
                    tools = ", ".join(tc["name"] for tc in m.tool_calls)
                    lines.append(f"AI（调用{tools}）：{content}")
                else:
                    lines.append(f"AI：{content}")
            elif isinstance(m, ToolMessage):
                lines.append(f"工具结果：{str(m.content)[:200]}")
        return "\n".join(lines)

    def summarize(self, state: dict) -> dict:
        """如果消息过长，压缩旧消息为摘要 SystemMessage"""
        messages = state.get("messages", [])
        if not self._should_summarize(messages):
            return state

        keep_count = self.keep["value"]
        old_messages = messages[:-keep_count]
        recent_messages = messages[-keep_count:]

        # Build conversation text for summarization
        conversation_text = self._format_for_summary(old_messages)
        if not conversation_text.strip():
            return state

        # Generate summary
        try:
            prompt = SUMMARIZE_PROMPT.format(conversation=conversation_text)
            response = self._client.chat.completions.create(
                model=self._model,
                messages=[{"role": "user", "content": prompt}],
                temperature=0.2,
                max_tokens=512,
                timeout=30,
            )
            summary_text = response.choices[0].message.content.strip()
        except Exception as e:
            logger.warning(f"Summary generation failed, truncating: {e}")
            # Fallback: simple truncation of old messages
            summary_text = conversation_text[:800] + "\n...（摘要生成失败，已截断）"

        # Replace old messages with summary SystemMessage
        summary_msg = SystemMessage(
            content=f"【对话历史摘要】\n{summary_text}"
        )
        new_messages = [summary_msg] + recent_messages

        logger.info(f"Summarized {len(old_messages)} messages into summary")
        return {**state, "messages": new_messages}