"""Golden management — versioned baselines for eval comparison.

Goldens are organized by version under the goldens/ directory:
  goldens/
    v1/
      manifest.json
      <golden files>
    v2/
      ...
"""
from __future__ import annotations

import json
from pathlib import Path
from typing import Any

DEFAULT_GOLDENS_DIR = Path(__file__).resolve().parent.parent.parent / "goldens"


def list_golden_versions(goldens_dir: Path | None = None) -> list[str]:
    """List available golden versions, sorted."""
    d = goldens_dir or DEFAULT_GOLDENS_DIR
    if not d.is_dir():
        return []
    return sorted(
        p.name for p in d.iterdir()
        if p.is_dir() and (p / "manifest.json").exists()
    )


def load_golden_set(version: str, goldens_dir: Path | None = None) -> dict[str, Any]:
    """Load a golden set by version name."""
    d = goldens_dir or DEFAULT_GOLDENS_DIR
    manifest_path = d / version / "manifest.json"
    if not manifest_path.exists():
        raise FileNotFoundError(f"Golden set not found: {version}")
    with open(manifest_path) as f:
        return json.load(f)


def diff_golden(
    golden_set: dict[str, Any],
    evidence_pack: dict[str, Any],
) -> list[dict[str, Any]]:
    """Compare evidence pack against golden set.

    Returns list of diff entries with:
      - key: the artifact key
      - status: "match" | "mismatch" | "missing_golden" | "missing_actual"
      - details: human-readable details
    """
    diffs = []
    golden_artifacts = golden_set.get("artifacts", {})
    actual_artifacts = evidence_pack.get("artifacts", {})

    all_keys = sorted(set(golden_artifacts.keys()) | set(actual_artifacts.keys()))

    for key in all_keys:
        if key not in golden_artifacts:
            diffs.append({
                "key": key,
                "status": "missing_golden",
                "details": "Artifact exists in actual but not in golden set",
            })
        elif key not in actual_artifacts:
            diffs.append({
                "key": key,
                "status": "missing_actual",
                "details": "Artifact exists in golden set but not in actual",
            })
        elif golden_artifacts[key] == actual_artifacts[key]:
            diffs.append({
                "key": key,
                "status": "match",
                "details": "Exact match",
            })
        else:
            diffs.append({
                "key": key,
                "status": "mismatch",
                "details": "Values differ",
            })

    return diffs


def bless_golden(
    version: str,
    evidence_pack: dict[str, Any],
    goldens_dir: Path | None = None,
    confirm_flag: bool = False,
) -> Path:
    """Promote evidence pack outputs to golden baseline.

    REQUIRES confirm_flag=True (CLI: --i-understand-this-changes-baselines)
    """
    if not confirm_flag:
        raise ValueError(
            "Bless requires explicit confirmation. "
            "Pass --i-understand-this-changes-baselines"
        )

    d = goldens_dir or DEFAULT_GOLDENS_DIR
    version_dir = d / version
    version_dir.mkdir(parents=True, exist_ok=True)

    manifest = {
        "version": version,
        "blessed_from": evidence_pack.get("run_id", "unknown"),
        "artifacts": evidence_pack.get("artifacts", {}),
    }

    manifest_path = version_dir / "manifest.json"
    with open(manifest_path, "w") as f:
        json.dump(manifest, f, indent=2, ensure_ascii=False, sort_keys=True)
        f.write("\n")

    return version_dir
