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

import argparse
import json
from pathlib import Path

import yaml


ROOT = Path(__file__).resolve().parents[1]
REQUIRED = {"request_id", "problem", "evidence", "target_metric", "affected_formula", "affected_output", "expected_side_effect", "rollback_plan", "test_cases"}


def main() -> int:
    ap = argparse.ArgumentParser()
    ap.add_argument("--dir", default="governance/change_requests")
    args = ap.parse_args()
    path = ROOT / args.dir
    errors: list[str] = []
    files = sorted(path.glob("*.yaml")) if path.exists() else []
    for file in files:
        data = yaml.safe_load(file.read_text(encoding="utf-8")) or {}
        missing = sorted(REQUIRED - set(data.keys()))
        if missing:
            errors.append(f"{file}: missing {missing}")
    result = {
        "formula_id": "CHANGE_REQUEST_COVERAGE_V1",
        "request_file_count": len(files),
        "missing_required_field_count": len(errors),
        "gate": "PASS" if not errors else "FAIL",
    }
    out = ROOT / "Temp" / "change_request_validation_v1.json"
    out.write_text(json.dumps(result, ensure_ascii=False, indent=2), encoding="utf-8")
    print(json.dumps(result, ensure_ascii=False, indent=2))
    for err in errors[:20]:
        print(err)
    return 0 if not errors else 1


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