"""Pre-computed vanilla baseline loader.

JL-160: Ships baseline files with PyPI package for offline comparison.
"""

import json
from pathlib import Path
from typing import Optional

from suite.result import BehaviorScore, BehaviorStatus, GovernanceFlags, SuiteResult

BASELINES_DIR = Path(__file__).parent / "baselines"


def list_baselines() -> list[dict]:
    """List all available pre-computed baselines."""
    baselines = []
    for f in sorted(BASELINES_DIR.glob("*.json")):
        data = json.loads(f.read_text(encoding="utf-8"))
        baselines.append({
            "filename": f.name,
            "agent": data.get("agent", ""),
            "model": data.get("model", ""),
            "score": data.get("aggregate", {}).get("average_score", 0),
            "grade": data.get("aggregate", {}).get("grade", "?"),
            "date": data.get("generated_at", "")[:10],
            "suite_version": data.get("suite", {}).get("version", ""),
        })
    return baselines


def find_baseline(
    agent: Optional[str] = None,
    model: Optional[str] = None,
) -> Optional[Path]:
    """Find the best matching baseline file.

    Priority: exact agent+model match > agent-only match (highest score) > best overall
    """
    candidates = sorted(BASELINES_DIR.glob("*.json"))

    # Exact match: filename starts with {agent}_{model}_
    if agent and model:
        for f in candidates:
            prefix = f"{agent}_{model}_"
            if f.stem.startswith(prefix):
                return f

    # Agent-only match: return highest scoring baseline for that agent
    if agent:
        best_score = -1.0
        best_file = None
        for f in candidates:
            if f.stem.startswith(f"{agent}_"):
                data = json.loads(f.read_text(encoding="utf-8"))
                score = data.get("aggregate", {}).get("average_score", 0)
                if score > best_score:
                    best_score = score
                    best_file = f
        return best_file

    # Fallback: best overall
    best_score = -1.0
    best_file = None
    for f in candidates:
        data = json.loads(f.read_text(encoding="utf-8"))
        score = data.get("aggregate", {}).get("average_score", 0)
        if score > best_score:
            best_score = score
            best_file = f
    return best_file


def load_baseline_as_suite_result(path: Path) -> SuiteResult:
    """Convert a baseline JSON file to SuiteResult for comparison.

    Baseline schema (benchmarks/schema.py) differs from SuiteResult:
    - Baseline: behaviors[].score (0-100), aggregate.average_score
    - SuiteResult: behavior_scores[].score (0-100), headline_score
    """
    data = json.loads(path.read_text(encoding="utf-8"))

    behavior_scores = []
    for b in data.get("behaviors", []):
        score = b.get("score")
        status_str = b.get("status", "passed")
        passed = status_str == "passed" and score is not None
        behavior_scores.append(
            BehaviorScore(
                behavior_id=b["behavior_id"],
                name=b.get("behavior_name", b["behavior_id"]),
                score=score,
                trust_elasticity=score,
                grade=b.get("grade", "?"),
                passed=passed,
                halted=False,
                status=BehaviorStatus.PASSED if passed else BehaviorStatus.FAILED,
            )
        )

    agg = data.get("aggregate", {})
    suite_info = data.get("suite", {})

    return SuiteResult(
        suite_id=suite_info.get("name", "refactor-storm"),
        suite_version=suite_info.get("version", "1.3.0"),
        config_fingerprint="vanilla-baseline",
        timestamp=data.get("generated_at", ""),
        headline_score=agg.get("average_score", 0.0),
        grade=agg.get("grade", "?"),
        behavior_scores=behavior_scores,
        governance_flags=GovernanceFlags(
            any_halted=False,
            halted_count=0,
            halted_behaviors=[],
            foundation_check_rate=0.0,
        ),
        comparability_key=f"{suite_info.get('name', 'refactor-storm')}-v{suite_info.get('version', '1.3.0')}",
        total_rollouts=len(behavior_scores),
        total_duration_ms=agg.get("total_duration_ms", 0),
        config_metadata=None,
    )
