"""Experience Schema - 任务经验数据模型

定义 TaskExperience 和 EvolutionMetrics 数据类，
用于存储任务执行经验和追踪进化指标趋势。
"""

from __future__ import annotations

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


@dataclass
class TaskExperience:
    """任务执行经验

    记录单次任务执行的关键信息，包括成功路径、失败原因、耗时等，
    支持按任务类型检索和语义搜索。

    Attributes:
        experience_id: 唯一标识
        task_type: 任务类型（如 "code_review", "data_analysis"）
        goal: 任务目标描述
        steps_summary: 执行步骤摘要
        outcome: 执行结果（"success" / "failure" / "partial"）
        duration_seconds: 执行耗时（秒）
        success_rate: 成功率（0.0 ~ 1.0）
        failure_reasons: 失败原因列表
        optimization_tips: 优化建议列表
        embedding: 语义向量（由 embedder 生成）
        created_at: 创建时间
    """

    experience_id: str = ""
    task_type: str = ""
    goal: str = ""
    steps_summary: str = ""
    outcome: str = "success"
    duration_seconds: float = 0.0
    success_rate: float = 1.0
    failure_reasons: list[str] = field(default_factory=list)
    optimization_tips: list[str] = field(default_factory=list)
    embedding: list[float] | None = None
    created_at: datetime = field(default_factory=lambda: datetime.now(timezone.utc))

    def to_dict(self) -> dict[str, Any]:
        """转换为字典（不含 embedding）"""
        return {
            "experience_id": self.experience_id,
            "task_type": self.task_type,
            "goal": self.goal,
            "steps_summary": self.steps_summary,
            "outcome": self.outcome,
            "duration_seconds": self.duration_seconds,
            "success_rate": self.success_rate,
            "failure_reasons": self.failure_reasons,
            "optimization_tips": self.optimization_tips,
            "created_at": self.created_at.isoformat(),
        }

    def text_for_embedding(self) -> str:
        """生成用于 embedding 的文本表示"""
        parts = [f"Task: {self.task_type}", f"Goal: {self.goal}"]
        if self.steps_summary:
            parts.append(f"Steps: {self.steps_summary}")
        if self.failure_reasons:
            parts.append(f"Failures: {'; '.join(self.failure_reasons)}")
        if self.optimization_tips:
            parts.append(f"Tips: {'; '.join(self.optimization_tips)}")
        return " | ".join(parts)


@dataclass
class EvolutionMetrics:
    """进化指标趋势

    追踪指定时间窗口内任务执行的完成率、平均耗时和重试率趋势。

    Attributes:
        task_type: 任务类型
        time_window: 时间窗口描述（如 "1h", "24h", "7d"）
        completion_rate: 完成率（0.0 ~ 1.0）
        avg_duration: 平均耗时（秒）
        retry_rate: 重试率（0.0 ~ 1.0）
        sample_count: 样本数量
        window_start: 窗口起始时间
        window_end: 窗口结束时间
    """

    task_type: str = ""
    time_window: str = "24h"
    completion_rate: float = 0.0
    avg_duration: float = 0.0
    retry_rate: float = 0.0
    sample_count: int = 0
    window_start: datetime = field(default_factory=lambda: datetime.now(timezone.utc))
    window_end: datetime = field(default_factory=lambda: datetime.now(timezone.utc))

    def to_dict(self) -> dict[str, Any]:
        """转换为字典"""
        return {
            "task_type": self.task_type,
            "time_window": self.time_window,
            "completion_rate": self.completion_rate,
            "avg_duration": self.avg_duration,
            "retry_rate": self.retry_rate,
            "sample_count": self.sample_count,
            "window_start": self.window_start.isoformat(),
            "window_end": self.window_end.isoformat(),
        }
