"""Policy override helpers for Autopilot."""

from __future__ import annotations

from datetime import datetime, timezone
from pathlib import Path

from .policy import AllowRule

try:  # Optional dependency in some environments.
    import yaml
except Exception as exc:  # pragma: no cover
    yaml = None  # type: ignore
    _yaml_import_error = exc
else:  # pragma: no cover - no error path when yaml present
    _yaml_import_error = None


def _ensure_yaml() -> None:
    if yaml is None:  # pragma: no cover
        raise RuntimeError("PyYAML is required for policy overrides.") from _yaml_import_error


def write_allow_rule_overlay(state_dir: Path, rule: AllowRule) -> Path:
    _ensure_yaml()
    overrides_dir = Path(state_dir) / "policy_overrides.d"
    overrides_dir.mkdir(parents=True, exist_ok=True)
    timestamp = datetime.now(timezone.utc).strftime("%Y%m%d_%H%M%S")
    safe_name = rule.name.replace(" ", "_").lower()
    path = overrides_dir / f"allow_{safe_name}_{timestamp}.yaml"
    payload = {"allow_rules": [rule.model_dump(exclude_none=True)]}
    with open(path, "w", encoding="utf-8") as f:
        yaml.safe_dump(payload, f, sort_keys=False, default_flow_style=False, allow_unicode=False)
    return path


def load_allow_rule_overlays(state_dir: Path) -> list[AllowRule]:
    _ensure_yaml()
    overrides_dir = Path(state_dir) / "policy_overrides.d"
    if not overrides_dir.exists():
        return []
    rules: list[AllowRule] = []
    for path in sorted(overrides_dir.glob("*.yaml")):
        try:
            with open(path, encoding="utf-8") as f:
                payload = yaml.safe_load(f) or {}
            for rule_data in payload.get("allow_rules", []) or []:
                rules.append(AllowRule.model_validate(rule_data))
        except Exception:
            continue
    return rules


__all__ = ["write_allow_rule_overlay", "load_allow_rule_overlays"]
