from __future__ import annotations

import argparse
import json
from pathlib import Path

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


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

    json_path = Path(args.json)
    if not json_path.is_absolute():
        json_path = ROOT / json_path

    if not json_path.exists():
        print(f"Sync json not found: {json_path}")
        return 1

    payload = json.loads(json_path.read_text(encoding="utf-8"))

    formula_id = payload.get("formula_id")
    gate = payload.get("gate")
    missing = payload.get("formula_domain_missing_count", 0)
    dup = payload.get("duplicate_formula_count", 0)
    dup_thresh = payload.get("duplicate_threshold_definition_count", 0)

    errors = []
    if formula_id != "FORMULA_REGISTRY_SYNC_V1":
        errors.append("Invalid formula_id")
    if gate != "PASS":
        errors.append(f"gate is {gate}")
    if missing != 0:
        errors.append(f"formula_domain_missing_count = {missing}")
    if dup != 0:
        errors.append(f"duplicate_formula_count = {dup}")
    if dup_thresh != 0:
        errors.append(f"duplicate_threshold_definition_count = {dup_thresh}")

    if errors:
        print("FORMULA_REGISTRY_SYNC_V1_FAIL")
        for err in errors:
            print(f"  {err}")
        return 1

    print("FORMULA_REGISTRY_SYNC_V1_OK")
    return 0


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