"""Reflector - 执行反思

每次任务完成后自动评估结果，提取模式，生成反思总结。
"""

import logging
from dataclasses import dataclass, field
from datetime import datetime, timezone
from typing import Any

from agentkit.core.protocol import TaskMessage, TaskResult, TaskStatus

logger = logging.getLogger(__name__)


@dataclass
class Reflection:
    """反思结果"""
    task_id: str
    agent_name: str
    outcome: str  # success / failure / partial
    quality_score: float  # 0.0 - 1.0
    patterns: list[str] = field(default_factory=list)
    insights: list[str] = field(default_factory=list)
    suggestions: list[str] = field(default_factory=list)
    created_at: datetime = field(default_factory=lambda: datetime.now(timezone.utc))


class RuleBasedReflector:
    """基于规则的执行反思器

    评估任务结果，提取成功/失败模式，生成改进建议。
    """

    def __init__(
        self,
        quality_scorer: Any | None = None,
        pattern_extractor: Any | None = None,
    ):
        self._quality_scorer = quality_scorer
        self._pattern_extractor = pattern_extractor

    async def reflect(self, task: TaskMessage, result: TaskResult) -> Reflection:
        """对任务执行结果进行反思"""
        # 判断结果
        outcome = "success" if result.status == TaskStatus.COMPLETED else "failure"

        # 质量评分
        quality_score = await self._score_quality(task, result)

        # 提取模式
        patterns = await self._extract_patterns(task, result, outcome)

        # 生成洞察
        insights = self._generate_insights(outcome, quality_score, patterns)

        # 生成建议
        suggestions = self._generate_suggestions(outcome, quality_score, patterns)

        reflection = Reflection(
            task_id=task.task_id,
            agent_name=result.agent_name,
            outcome=outcome,
            quality_score=quality_score,
            patterns=patterns,
            insights=insights,
            suggestions=suggestions,
        )

        logger.info(
            f"Reflection for task {task.task_id}: outcome={outcome}, "
            f"quality={quality_score:.2f}, patterns={len(patterns)}"
        )

        return reflection

    async def _score_quality(self, task: TaskMessage, result: TaskResult) -> float:
        """评估任务质量"""
        if result.status != TaskStatus.COMPLETED:
            return 0.0

        if self._quality_scorer:
            return await self._quality_scorer(task, result)

        # 默认评分逻辑
        score = 0.5  # 基础分

        # 有输出数据加分
        if result.output_data:
            score += 0.2

        # 无错误加分
        if not result.error_message:
            score += 0.1

        # 耗时合理加分
        if result.metrics and result.metrics.get("elapsed_seconds", 0) < 30:
            score += 0.2

        return min(score, 1.0)

    async def _extract_patterns(
        self, task: TaskMessage, result: TaskResult, outcome: str
    ) -> list[str]:
        """提取模式"""
        patterns = []

        if outcome == "failure":
            if result.error_message:
                patterns.append(f"error_type:{type(result.error_message).__name__}")
            if result.metrics and result.metrics.get("elapsed_seconds", 0) > 60:
                patterns.append("slow_execution")
        else:
            if result.output_data and len(result.output_data) > 5:
                patterns.append("rich_output")
            if result.metrics and result.metrics.get("elapsed_seconds", 0) < 10:
                patterns.append("fast_execution")

        return patterns

    def _generate_insights(
        self, outcome: str, quality_score: float, patterns: list[str]
    ) -> list[str]:
        """生成洞察"""
        insights = []

        if quality_score < 0.3:
            insights.append("Low quality score indicates potential issues with task execution")
        if "slow_execution" in patterns:
            insights.append("Slow execution may benefit from strategy optimization")
        if "error_type:TimeoutError" in patterns:
            insights.append("Timeout errors suggest need for longer timeout or task decomposition")

        return insights

    def _generate_suggestions(
        self, outcome: str, quality_score: float, patterns: list[str]
    ) -> list[str]:
        """生成改进建议"""
        suggestions = []

        if outcome == "failure" and quality_score < 0.3:
            suggestions.append("Consider prompt optimization for this task type")
        if "slow_execution" in patterns:
            suggestions.append("Consider adjusting strategy parameters for faster execution")

        return suggestions


# 向后兼容别名
Reflector = RuleBasedReflector
