"""优化历史 YAML 读写。"""

from __future__ import annotations

from datetime import datetime, timezone
from pathlib import Path

import yaml


class HistoryManager:
    """管理 .promptgrad/history.yaml。"""

    def __init__(self, history_path: str):
        self.history_path = Path(history_path)

    def load(self) -> list[dict]:
        """加载历史记录。文件不存在则返回空列表。"""
        if not self.history_path.exists():
            return []
        with open(self.history_path, "r", encoding="utf-8") as f:
            data = yaml.safe_load(f)
        if not data or "history" not in data:
            return []
        return data["history"]

    def add_entry(
        self,
        version: int,
        scores: dict,
        pass_rate: float,
        changelog: str,
        hypothesis: str | None = None,
        regression_check: str | None = None,
    ) -> None:
        """追加一条历史记录。"""
        entries = self.load()
        entry: dict = {
            "version": version,
            "timestamp": datetime.now(timezone.utc).isoformat(),
            "scores": scores,
            "pass_rate": round(pass_rate, 4),
            "changelog": changelog,
        }
        if hypothesis:
            entry["hypothesis"] = hypothesis
        if regression_check:
            entry["regression_check"] = regression_check
        entries.append(entry)
        self._save(entries)

    def get_score_history(self) -> list[float]:
        """返回每轮的 avg_score 列表。"""
        return [e["scores"]["avg"] for e in self.load()]

    def save_prompt_snapshot(self, prompt_config: dict, version: int, prompts_dir: str) -> None:
        """保存 prompt 版本快照。"""
        p = Path(prompts_dir)
        p.mkdir(parents=True, exist_ok=True)
        snapshot_path = p / f"v{version}.yaml"
        with open(snapshot_path, "w", encoding="utf-8") as f:
            yaml.dump(prompt_config, f, default_flow_style=False, allow_unicode=True, sort_keys=False)

    def _save(self, entries: list[dict]) -> None:
        """写入历史文件。"""
        self.history_path.parent.mkdir(parents=True, exist_ok=True)
        with open(self.history_path, "w", encoding="utf-8") as f:
            yaml.dump({"history": entries}, f, default_flow_style=False, allow_unicode=True, sort_keys=False)
