#!/usr/bin/env python3
"""Verify a CAIN-42 release-readiness scorecard offline. Standard library + `cryptography`; imports no CAIN code.

    pip install cryptography
    curl -fsSLO https://cainstudio.online/verify_release_readiness.py
    curl -fsSLO https://cainstudio.online/evidence/release-readiness/record.json
    python3 -I verify_release_readiness.py record.json

Checks, all on your machine:
  1. KEY      the pinned public key has the published fingerprint
  2. SIG      the Ed25519 signature is valid for the exact signed bytes
  3. HASH     record_sha256 is the SHA-256 of those bytes
  4. VERDICT  the overall verdict is recomputed from the per-criterion statuses (GA only if every criterion is MET;
              otherwise PUBLIC_BETA) and must match what the record claims
Exit 0 only when all four pass. This proves the scorecard is authentic and its verdict is not inflated past its own
criteria; it does NOT prove the criteria themselves (an external audit and real customers are off-chain facts).
"""
from __future__ import annotations

import argparse
import base64
import hashlib
import json
import sys

PUBLIC_KEY_B64 = "b6hfA2rpAdV29FOdhNXGkk4t91mCV0AnfFYwq0HO0R8="
FINGERPRINT = "SHA256:2232b4add9b35d4016e5be270df4ed56e0dc9b39a0530ac69891073253aae90d"


def recompute_verdict(criteria):
    statuses = [c.get("status") for c in criteria]
    if all(s == "MET" for s in statuses) and statuses:
        return "GA"
    return "PUBLIC_BETA"


def main(argv=None) -> int:
    ap = argparse.ArgumentParser(description=__doc__.splitlines()[0])
    ap.add_argument("record")
    ap.add_argument("--public-key", default=PUBLIC_KEY_B64)
    ap.add_argument("--fingerprint", default=FINGERPRINT)
    ap.add_argument("--json", action="store_true")
    a = ap.parse_args(argv)
    checks = []

    def add(n, ok, detail=""):
        checks.append({"check": n, "ok": bool(ok), "detail": detail})
        return ok

    try:
        from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PublicKey
    except ImportError:
        print("needs: pip install cryptography", file=sys.stderr)
        return 2
    rec = json.load(open(a.record))
    raw = base64.b64decode(a.public_key)
    fp = "SHA256:" + hashlib.sha256(raw).hexdigest()
    add("KEY", fp.lower() == a.fingerprint.strip().lower(), fp)
    sig = rec.get("signature", {})
    body = {k: rec[k] for k in rec if k not in ("record_sha256", "signature", "signed_payload_b64")}
    payload = json.dumps(body, sort_keys=True, separators=(",", ":")).encode()
    try:
        Ed25519PublicKey.from_public_bytes(raw).verify(base64.b64decode(sig["sig_b64"]), payload)
        add("SIG", True, sig.get("key_fingerprint", ""))
    except Exception as e:  # noqa: BLE001
        add("SIG", False, type(e).__name__)
    add("HASH", rec.get("record_sha256") == hashlib.sha256(payload).hexdigest(), rec.get("record_sha256", "")[:16])
    want = recompute_verdict(rec.get("criteria", []))
    add("VERDICT", want == rec.get("overall_verdict"), f"recomputed={want} claimed={rec.get('overall_verdict')}")
    ok = all(c["ok"] for c in checks)
    if a.json:
        print(json.dumps({"ok": ok, "checks": checks, "overall_verdict": rec.get("overall_verdict"),
                          "criteria": [(c.get("name"), c.get("status")) for c in rec.get("criteria", [])]}, indent=2))
    else:
        for c in checks:
            print(f"  {'PASS' if c['ok'] else 'FAIL'}  {c['check']:8s} {c['detail']}")
        print(f"\nCAIN-42 release stage: {rec.get('overall_verdict')}")
        for c in rec.get("criteria", []):
            print(f"  [{c.get('status'):8s}] {c.get('name')}")
        print("VERIFIED" if ok else "NOT VERIFIED")
    return 0 if ok else 1


if __name__ == "__main__":
    sys.exit(main())
