from __future__ import annotations

import json
from pathlib import Path

from beaver.memory.skills import (
    SkillDraftEvalReport,
    SkillDraftSafetyReport,
    SkillLearningCandidate,
    SkillLearningStore,
)


def test_candidate_state_update_and_audit_order(tmp_path: Path) -> None:
    store = SkillLearningStore(tmp_path)
    store.record_learning_candidate(
        SkillLearningCandidate(
            candidate_id="candidate-1",
            kind="new_skill",
            source_run_ids=["run-1"],
            source_session_ids=["session-1"],
            related_skill_names=[],
            reason="repeat success",
            confidence=0.8,
        )
    )

    queued = store.transition_learning_candidate("candidate-1", "queued", event_type="candidate_queued")
    ready = store.transition_learning_candidate(
        "candidate-1",
        "draft_ready",
        event_type="draft_synthesis_completed",
        draft_skill_name="repeat-success",
        draft_id="draft-1",
    )

    assert queued is not None
    assert ready is not None
    assert ready.status == "draft_ready"
    assert ready.draft_id == "draft-1"

    events = store.list_audit_events("candidate-1")
    assert [event.event_type for event in events] == [
        "candidate_created",
        "candidate_queued",
        "draft_synthesis_completed",
    ]


def test_legacy_candidate_payload_is_backward_compatible(tmp_path: Path) -> None:
    path = tmp_path / "learning-candidates.jsonl"
    path.write_text(
        json.dumps(
            {
                "candidate_id": "legacy-1",
                "kind": "revise_skill",
                "source_run_ids": ["run-1"],
                "source_session_ids": [],
                "related_skill_names": ["debug"],
                "reason": "old shape",
                "evidence": {"skill_version": "v0001"},
                "status": "open",
            }
        )
        + "\n",
        encoding="utf-8",
    )

    candidate = SkillLearningStore(tmp_path).list_learning_candidates()[0]

    assert candidate.candidate_id == "legacy-1"
    assert candidate.priority == 0
    assert candidate.risk_level == "medium"
    assert candidate.evidence_summary == "Skill version: v0001"
    assert candidate.created_at
    assert candidate.updated_at


def test_safety_and_eval_reports_round_trip(tmp_path: Path) -> None:
    store = SkillLearningStore(tmp_path)
    safety = SkillDraftSafetyReport(
        report_id="safety-1",
        skill_name="debug",
        draft_id="draft-1",
        passed=True,
        risk_level="low",
        created_at="now",
    )
    eval_report = SkillDraftEvalReport(
        report_id="eval-1",
        skill_name="debug",
        draft_id="draft-1",
        candidate_id="candidate-1",
        passed=True,
        baseline_score_avg=0.7,
        candidate_score_avg=0.9,
        score_delta=0.2,
        regression_count=0,
        improved_count=1,
        unchanged_count=0,
        cases=[{"run_id": "run-1"}],
        created_at="now",
    )

    store.write_safety_report(safety)
    store.write_eval_report(eval_report)

    assert store.get_safety_report("debug", "draft-1").report_id == "safety-1"  # type: ignore[union-attr]
    assert store.get_eval_report("debug", "draft-1").report_id == "eval-1"  # type: ignore[union-attr]
