"""Validation snapshot — proof artifact for production qualification.

Writes a ``.validated.yaml`` sidecar next to the suite file recording:
- Pass rate, case counts, timing
- Model config at validation time
- Content hashes of tool files

If the model config or hashed components change, re-validation is needed.
"""

from __future__ import annotations

import hashlib
import time
from pathlib import Path
from typing import Any

import yaml

from core.validation.models import ValidationResult


def write_snapshot(
    result: ValidationResult,
    suite_path: str | Path,
) -> Path:
    """Write a .validated.yaml snapshot next to the suite file.

    Args:
        result: The validation result to snapshot.
        suite_path: Path to the original suite YAML.

    Returns
    -------
        Path to the written snapshot file.
    """
    suite_path = Path(suite_path).resolve()
    snapshot_path = suite_path.with_suffix(".validated.yaml")

    model_config = _capture_model_config()
    component_hashes = _compute_component_hashes()

    snapshot: dict[str, Any] = {
        "suite": result.suite_id,
        "validated_at": time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()),
        "pass_rate": round(result.cases_passed / max(result.cases_run, 1), 2),
        "cases_run": result.cases_run,
        "cases_passed": result.cases_passed,
        "cases_failed": result.cases_failed,
        "duration_ms": result.total_duration_ms,
        "model_config": model_config,
        "component_hashes": component_hashes,
    }

    with open(snapshot_path, "w") as f:
        yaml.dump(snapshot, f, default_flow_style=False, sort_keys=False)

    return snapshot_path


def _capture_model_config() -> dict[str, str]:
    """Capture the current effective model routing config."""
    try:
        from stdlib.llm.routing import get_runtime_model_config

        config = get_runtime_model_config()
        return config.get("effective", {})
    except Exception:
        return {}


def _compute_component_hashes() -> dict[str, str]:
    """Compute content hashes for key tool files.

    Used to detect when components have changed since validation.
    """
    hashes: dict[str, str] = {}

    # Knowledge tool files
    knowledge_dir = (
        Path(__file__).resolve().parents[2]
        / "stdlib" / "primitives" / "tools" / "knowledge" / "tools"
    )
    if knowledge_dir.exists():
        combined = b""
        for py_file in sorted(knowledge_dir.glob("*.py")):
            combined += py_file.read_bytes()
        if combined:
            hashes["knowledge_tools"] = hashlib.sha256(combined).hexdigest()[:12]

    return hashes
