"""History 模块测试。"""

import yaml

from promptgrad.history import HistoryManager


class TestHistoryManager:
    def test_load_empty(self, tmp_promptgrad_dir):
        hm = HistoryManager(str(tmp_promptgrad_dir / "history.yaml"))
        entries = hm.load()
        assert entries == []

    def test_add_and_load(self, tmp_promptgrad_dir):
        hm = HistoryManager(str(tmp_promptgrad_dir / "history.yaml"))
        hm.add_entry(
            version=1,
            scores={"avg": 0.62, "relevance": 0.70},
            pass_rate=0.45,
            changelog="initial version",
        )
        entries = hm.load()
        assert len(entries) == 1
        assert entries[0]["version"] == 1
        assert entries[0]["scores"]["avg"] == 0.62
        assert "timestamp" in entries[0]

    def test_add_multiple(self, tmp_promptgrad_dir):
        hm = HistoryManager(str(tmp_promptgrad_dir / "history.yaml"))
        hm.add_entry(version=1, scores={"avg": 0.5}, pass_rate=0.3, changelog="v1")
        hm.add_entry(
            version=2,
            scores={"avg": 0.7},
            pass_rate=0.6,
            changelog="v2",
            hypothesis="test",
            regression_check="pass",
        )
        entries = hm.load()
        assert len(entries) == 2
        assert entries[1]["hypothesis"] == "test"
        assert entries[1]["regression_check"] == "pass"

    def test_get_latest_scores(self, tmp_promptgrad_dir):
        hm = HistoryManager(str(tmp_promptgrad_dir / "history.yaml"))
        hm.add_entry(version=1, scores={"avg": 0.5}, pass_rate=0.3, changelog="v1")
        hm.add_entry(version=2, scores={"avg": 0.7}, pass_rate=0.6, changelog="v2")
        scores = hm.get_score_history()
        assert scores == [0.5, 0.7]

    def test_save_prompt_snapshot(self, tmp_promptgrad_dir):
        hm = HistoryManager(str(tmp_promptgrad_dir / "history.yaml"))
        prompt_config = {"system": "test", "template": "{{q}}", "few_shot_examples": []}
        hm.save_prompt_snapshot(prompt_config, 1, str(tmp_promptgrad_dir / "prompts"))
        snapshot_path = tmp_promptgrad_dir / "prompts" / "v1.yaml"
        assert snapshot_path.exists()
        data = yaml.safe_load(snapshot_path.read_text())
        assert data["system"] == "test"
