from __future__ import annotations

from dataclasses import dataclass
from typing import Any, Dict, Optional
import importlib.resources as resources


@dataclass(frozen=True)
class Policy:
    name: str
    data: Dict[str, Any]


def load_policy(package_yaml_name: str, *, override_path: Optional[str] = None) -> Policy:
    """
    Load a YAML policy either from:
      - a local override_path (recommended for enterprise usage), OR
      - bundled package policy file under agent_sentinel/policies/

    package_yaml_name examples:
      - "finops_policy.yaml"
      - "procurement_policy.yaml"
    """
    try:
        import yaml  # type: ignore
    except Exception as e:
        raise RuntimeError(
            "PyYAML is required to load policy YAML. Install with: pip install PyYAML"
        ) from e

    if override_path:
        with open(override_path, "r", encoding="utf-8") as f:
            data = yaml.safe_load(f) or {}
        return Policy(name=package_yaml_name, data=data)

    pkg = "agent_sentinel.policies"
    with resources.open_text(pkg, package_yaml_name, encoding="utf-8") as f:
        data = yaml.safe_load(f) or {}

    return Policy(name=package_yaml_name, data=data)
