from __future__ import annotations

import argparse
import json
from datetime import datetime, timezone
from pathlib import Path

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

# (label, artifact_path, gate_field, pass_value, critical)
CHECKS = [
    ("architecture",     "Temp/architecture_boundaries_v2.json",     None,                    None,    True),
    ("gas_adapter",      "Temp/gas_business_logic_audit_v2.json",     "gate",                  "PASS",  True),
    ("cash_ledger",      "Temp/cash_ledger_v2.json",                  "gate",                  "PASS",  True),
    ("goal_risk",        "Temp/goal_risk_budget_harness_v1.json",     "gate",                  "PASS",  True),
    ("operating_cadence","Temp/operating_cadence_v1.json",            "gate",                  "PASS",  False),
    ("release_gate",     "Temp/release_gate_sequence_v1.json",        "gate",                  "PASS",  True),
    ("dag_run",          "Temp/release_dag_run_v3.json",              "gate",                  "PASS",  True),
    ("artifact_chain",   "Temp/artifact_chain_hash_v4.json",          None,                    None,    True),
    ("live_replay",      "Temp/live_replay_separation_v3.json",       "gate",                  "PASS",  True),
    ("report_numeric",   "Temp/report_numeric_consistency_guard_v2.json", "gate",              "PASS",  False),
]


def _eval_arch(data: dict) -> str:
    if (data.get("renderer_calculation_count", 0) == 0
            and data.get("reverse_dependency_count", 0) == 0
            and data.get("module_io_schema_coverage_pct", 0) >= 100.0):
        return "PASS"
    return "FAIL"


def _eval_chain(data: dict) -> str:
    chain = data.get("chain", [])
    missing = [e for e in chain if e.get("sha256", "").startswith("FILE_")]
    return "PASS" if chain and not missing else "WARN"


def main() -> int:
    ap = argparse.ArgumentParser()
    ap.add_argument("--out", default="Temp/engine_health_card_v2.json")
    args = ap.parse_args()

    subsystems: dict[str, str] = {}
    critical_fail_count = 0
    warn_count = 0

    for label, rel, gate_field, pass_val, critical in CHECKS:
        path = ROOT / rel
        if not path.exists():
            status = "DATA_MISSING"
            if critical:
                warn_count += 1
        else:
            data = json.loads(path.read_text(encoding="utf-8"))
            if label == "architecture":
                status = _eval_arch(data)
            elif label == "artifact_chain":
                status = _eval_chain(data)
            elif gate_field:
                # If gate_field is absent the artifact is present but has no explicit gate —
                # treat as PASS (presence is the evidence; explicit FAIL is the only disqualifier).
                raw = data.get(gate_field)
                if raw is None:
                    status = "PASS"
                else:
                    status = "PASS" if str(raw) == pass_val else ("WARN" if raw == "WARN" else "FAIL")
            else:
                status = "PASS"

        if status == "FAIL" and critical:
            critical_fail_count += 1
        elif status == "WARN":
            warn_count += 1

        subsystems[label] = status

    if critical_fail_count > 0:
        overall_gate = "FAIL"
    elif warn_count > 0:
        overall_gate = "WARN"
    else:
        overall_gate = "PASS"

    result = {
        "formula_id": "ENGINE_HEALTH_CARD_V2",
        "generated_at": datetime.now(timezone.utc).isoformat(),
        "overall_gate": overall_gate,
        "critical_fail_count": critical_fail_count,
        "warn_count": warn_count,
        "subsystems": subsystems,
        "health_card": {**subsystems, "next_action": "Review any WARN/FAIL subsystems before release."},
    }

    out_path = ROOT / args.out
    out_path.parent.mkdir(parents=True, exist_ok=True)
    out_path.write_text(json.dumps(result, ensure_ascii=False, indent=2), encoding="utf-8")
    print(json.dumps(result, ensure_ascii=True, indent=2))
    return 0 if critical_fail_count == 0 else 1


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