"""Utility functions for policy management."""

from typing import Any

from ..schemas import CompiledCoveragePolicy, CoveragePolicy, ValidationResult
from .loader import PolicyLoader

# Global policy loader instance
_policy_loader: PolicyLoader | None = None


def get_policy_loader(config_dir: str = "config") -> PolicyLoader:
    """Get global policy loader instance"""
    global _policy_loader
    if _policy_loader is None:
        _policy_loader = PolicyLoader(config_dir)
    return _policy_loader


# Convenience functions
def load_policy(
    baseline_path: str | None = None,
    jurisdiction: str = "UK",
    tax_year: str = "2024-25",
    tenant_id: str | None = None,
) -> CoveragePolicy:
    """Load coverage policy with overlays"""
    return get_policy_loader().load_policy(
        baseline_path, jurisdiction, tax_year, tenant_id
    )


def merge_overlays(base: dict[str, Any], *overlays: dict[str, Any]) -> dict[str, Any]:
    """Merge base policy with overlays"""
    return get_policy_loader().merge_overlays(base, *overlays)


def apply_feature_flags(policy: dict[str, Any]) -> dict[str, Any]:
    """Apply feature flags to policy"""
    return get_policy_loader().apply_feature_flags(policy)


def compile_predicates(policy: CoveragePolicy) -> CompiledCoveragePolicy:
    """Compile policy predicates"""
    return get_policy_loader().compile_predicates(policy)


def validate_policy(policy_dict: dict[str, Any]) -> ValidationResult:
    """Validate policy"""
    return get_policy_loader().validate_policy(policy_dict)
