from typing import Any, Dict, Optional
import json
import pathlib
import yaml
from .core import evaluate
from .sources.registry import CrossChecker
from .audit.schema import AuditReport

class Verdict:
    def __init__(self, ok: bool, report: AuditReport) -> None:
        self.ok = ok
        self.report = report
        self.summary = json.dumps(report.model_dump(), ensure_ascii=False, indent=2)

def load_rules(path: Optional[str]) -> Dict[str, Any]:
    if not path:
        text = (pathlib.Path(__file__).parent / "policies" / "default_rules.yaml").read_text(encoding="utf-8")
        return yaml.safe_load(text)
    data = pathlib.Path(path).read_text(encoding="utf-8")
    return yaml.safe_load(data)

def enforce_policy(payload: str, rules_path: Optional[str], audit_out: str, strict_fail: bool) -> Verdict:
    rules = load_rules(rules_path)
    checker = CrossChecker(rules)
    report = evaluate(payload=payload, rules=rules, checker=checker)
    pathlib.Path(audit_out).write_text(json.dumps(report.model_dump(), ensure_ascii=False, indent=2), encoding="utf-8")
    return Verdict(report.ok if not strict_fail else (report.ok and checker.ok), report)
