#!/usr/bin/env python3
from __future__ import annotations

import argparse
import json
from pathlib import Path

import yaml

from audit_repository_entropy_v1 import _iter_files, _sha256_file, _zip_sha256


ROOT = Path(__file__).resolve().parents[1]


def _load_budget(path: Path) -> dict:
    if not path.exists():
        return {}
    try:
        data = yaml.safe_load(path.read_text(encoding="utf-8"))
        return data if isinstance(data, dict) else {}
    except Exception:
        return {}


def main() -> int:
    ap = argparse.ArgumentParser()
    ap.add_argument("--root", default=".")
    ap.add_argument("--out", required=True)
    ap.add_argument("--budget", default="spec/release/repository_entropy_budget.yaml")
    args = ap.parse_args()
    root = Path(args.root).resolve()
    budget = _load_budget(ROOT / args.budget)
    files = _iter_files(root)
    package_json = root / "package.json"
    script_count = 0
    if package_json.exists():
        try:
            pkg = json.loads(package_json.read_text(encoding="utf-8"))
            scripts = pkg.get("scripts") if isinstance(pkg, dict) else {}
            script_count = len(scripts) if isinstance(scripts, dict) else 0
        except Exception:
            script_count = 0
    file_budget = int(budget.get("max_total_files") or 10**9)
    script_budget = int(budget.get("max_package_scripts") or 10**9)
    temp_budget = int(budget.get("max_temp_json_files") or 10**9)
    temp_count = len([p for p in (root / "Temp").glob("*.json")]) if (root / "Temp").exists() else 0
    gate = "PASS" if len(files) <= file_budget and script_count <= script_budget and temp_count <= temp_budget else "FAIL"
    payload = {
        "formula_id": "AUDIT_REPOSITORY_ENTROPY_V2",
        "gate": gate,
        "total_file_count": len(files),
        "package_script_count": script_count,
        "temp_json_count": temp_count,
        "budget": budget,
        "source_zip_sha256": _zip_sha256(root),
    }
    out = Path(args.out)
    out.parent.mkdir(parents=True, exist_ok=True)
    out.write_text(json.dumps(payload, ensure_ascii=False, indent=2), encoding="utf-8")
    print(json.dumps(payload, ensure_ascii=False, indent=2))
    return 0 if gate == "PASS" else 1


if __name__ == "__main__":
    raise SystemExit(main())
