"""Load and save the triage policy."""

from pathlib import Path

import yaml
from pydantic import ValidationError

from noisegate.exceptions import PolicyParseError
from noisegate.models import CheckResult, Policy, Verdict


def load_policy(path: Path) -> Policy:
    try:
        raw = yaml.safe_load(path.read_text())
    except (yaml.YAMLError, OSError) as exc:
        raise PolicyParseError(path, str(exc)) from exc
    try:
        return Policy.model_validate(raw)
    except ValidationError as exc:
        raise PolicyParseError(path, str(exc)) from exc


def save_policy(policy: Policy, path: Path) -> None:
    path.parent.mkdir(parents=True, exist_ok=True)
    path.write_text(yaml.dump(policy.model_dump(), sort_keys=False, allow_unicode=True))


def derive_verdict(checks: list[CheckResult], policy: Policy) -> Verdict:
    """Derive a verdict from check results and policy hard_fail configuration."""
    hard_fail_ids = {c.id for c in policy.checks if c.hard_fail}
    if any(not r.passed and r.check_id in hard_fail_ids for r in checks):
        return Verdict.FAIL
    if any(not r.passed for r in checks):
        return Verdict.WARN
    return Verdict.PASS
