"""Policy loader — reads .apiposture-policy.json from the scanned directory."""

from __future__ import annotations

import json
from dataclasses import dataclass, field
from pathlib import Path


@dataclass
class PolicyConfig:
    """Parsed policy configuration."""

    zero_tolerance: list[str] = field(default_factory=list)
    warn: list[str] = field(default_factory=list)
    fail_on: str = "high"  # critical | high | medium | low


SEVERITY_ORDER = ["critical", "high", "medium", "low", "info"]


def load_policy(scan_path: Path) -> PolicyConfig | None:
    """
    Load policy config from .apiposture-policy.json in scan_path or any parent.

    Returns None if no policy file is found.
    """
    check = scan_path.resolve()
    for directory in [check] + list(check.parents):
        candidate = directory / ".apiposture-policy.json"
        if candidate.exists():
            return _parse_policy(candidate)
        # Stop at filesystem root
        if directory == directory.parent:
            break
    return None


def _parse_policy(path: Path) -> PolicyConfig:
    """Parse policy JSON file into PolicyConfig."""
    with open(path, encoding="utf-8") as f:
        data = json.load(f)

    zero_tolerance = data.get("zero_tolerance", [])
    warn = data.get("warn", [])
    fail_on = data.get("fail_on", "high")

    # Validate fail_on
    if fail_on not in SEVERITY_ORDER:
        fail_on = "high"

    return PolicyConfig(
        zero_tolerance=[str(r) for r in zero_tolerance],
        warn=[str(r) for r in warn],
        fail_on=fail_on,
    )
