from __future__ import annotations

import argparse
import json
from pathlib import Path
from typing import Any


ROOT = Path(__file__).resolve().parents[1]
DEFAULT_PATH = ROOT / "Temp" / "data_maturity_truth_gate_v1.json"


def _load(path: Path) -> dict[str, Any]:
    if not path.exists():
        return {}
    try:
        obj = json.loads(path.read_text(encoding="utf-8"))
    except Exception:
        return {}
    return obj if isinstance(obj, dict) else {}


def main() -> int:
    ap = argparse.ArgumentParser()
    ap.add_argument("--json", default=str(DEFAULT_PATH))
    args = ap.parse_args()

    path = Path(args.json)
    if not path.is_absolute():
        path = ROOT / path
    payload = _load(path)

    failed: list[str] = []
    if float(payload.get("data_integrity_score") or 0) < 100.0:
        failed.append("DATA_INTEGRITY_LT_100")
    if float(payload.get("required_field_completeness_pct") or 0) < 100.0:
        failed.append("REQUIRED_FIELD_COMPLETENESS_LT_100")
    if int(payload.get("pending_critical_category_count") or 0) != 3:
        failed.append("PENDING_CATEGORY_COUNT_MISMATCH")
    if float(payload.get("data_maturity_score") or 0) < 95.0:
        failed.append("DATA_MATURITY_LT_95")
    if int(payload.get("no_false_100_claim_count") or 0) != 0:
        failed.append("FALSE_100_CLAIM_PRESENT")

    result = {
        "formula_id": "DATA_MATURITY_TRUTH_GATE_VALIDATOR_V1",
        "status": "OK" if not failed else "FAIL",
        "failed": failed,
        "gate": payload.get("gate"),
        "data_maturity_score": payload.get("data_maturity_score"),
    }
    print(json.dumps(result, ensure_ascii=False, indent=2))
    return 1 if failed else 0


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