#!/usr/bin/env python3
"""Audits the legacy public file cain_cluster_4node_bft_evidence.json against what its named endpoints actually report NOW.

Read-only: GET /health, /api/v1/cluster/status and /api/v1/cluster/pbft/status on every endpoint the file names. Records raw key fields with a timestamp so
anyone can repeat the same GETs. Mechanical checks only (no opinion): does each claim carry any attached evidence (a signature, digest, artifact path)? do live values
match the file's values? Writes CAIN42_LEGACY_CLUSTER_CLAIM_AUDIT.json. Anything unreachable is recorded UNREACHABLE, never assumed."""
import hashlib, json, os, time, urllib.request

ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
SRC = os.path.join(ROOT, "platform-gateway", "frontend", "proof", "bundle", "v2", "cain_cluster_4node_bft_evidence.json")
OUT = os.path.join(ROOT, "CAIN42_LEGACY_CLUSTER_CLAIM_AUDIT.json")


def get(url):
    try:
        r = urllib.request.urlopen(url, timeout=8)
        body = r.read()
        try:
            return r.status, json.loads(body)
        except Exception:
            return r.status, None
    except urllib.error.HTTPError as e:
        return e.code, None
    except Exception as e:
        return None, type(e).__name__


def has_evidence(o):
    """True if any key in the subtree looks like attached evidence (signature / digest / hash / artifact path)."""
    if isinstance(o, dict):
        return any(any(w in k.lower() for w in ("signature", "digest", "sha256", "merkle", "artifact", "proof_url", "evidence_path")) or has_evidence(v) for k, v in o.items())
    if isinstance(o, list):
        return any(has_evidence(x) for x in o)
    return False


def main():
    raw = open(SRC, "rb").read()
    d = json.loads(raw)
    topo = d["cluster_topology"]
    probes = []
    for n in topo["nodes"]:
        base = n["endpoint"]
        rec = {"node_id": n["node_id"], "endpoint": base, "claimed_state": n.get("state")}
        for name, path in (("health", "/health"), ("cluster_status", "/api/v1/cluster/status"), ("pbft_status", "/api/v1/cluster/pbft/status")):
            code, body = get(base + path)
            rec[name + "_http"] = code
            if name == "cluster_status" and isinstance(body, dict):
                rec["observed"] = {k: body.get(k) for k in ("node_id", "cluster_id", "node_count", "healthy_nodes", "quorum", "is_quorum", "can_tolerate_byzantine")}
            if name == "pbft_status" and isinstance(body, dict):
                rec["pbft_observed"] = {k: body.get(k) for k in ("cluster_id", "quorum_size", "fault_tolerance_f", "cluster_size_n", "view", "sequence")}
        probes.append(rec)
    claims = []
    for inv in d["consensus_and_security_invariants"]["invariants"]:
        claims.append({"id": inv["id"], "name": inv["name"], "claimed_result": inv["result"], "evidence_attached_in_file": has_evidence(inv)})
    reach = [p for p in probes if p.get("cluster_status_http") == 200]
    ids = {p["observed"]["cluster_id"] for p in reach if "observed" in p}
    quorums = {p["node_id"]: p["observed"]["quorum"] for p in reach if "observed" in p}
    audit = {
        "schema": "cain42.legacy_cluster_claim_audit.v1", "audited_at": time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()),
        "audited_file": "cain_cluster_4node_bft_evidence.json", "audited_file_sha256": hashlib.sha256(raw).hexdigest(),
        "file_claims": {"cluster_id": d["cluster_id"], "status": d["status"], "quorum_threshold": topo["quorum_threshold"], "f": topo["byzantine_fault_tolerance_f"],
                        "byzantine_f1_readiness": topo["byzantine_f1_readiness"], "invariants_status": d["consensus_and_security_invariants"]["status"]},
        "probes": probes, "invariant_claims": claims,
        "checks": {
            "endpoints_reachable": f"{len(reach)}/{len(probes)}",
            "observed_cluster_ids": sorted(ids), "cluster_id_matches_file": ids == {d["cluster_id"]} if ids else None,
            "observed_quorum_per_node": quorums,
            "observed_quorum_meets_file_claim_of_3": all(q >= topo["quorum_threshold"] for q in quorums.values()) if quorums else None,
            "nodes_exposing_pbft_status": [p["node_id"] for p in probes if p.get("pbft_observed")],
            "invariants_with_attached_evidence": sum(c["evidence_attached_in_file"] for c in claims), "invariants_claimed": len(claims),
        },
        "verdict": None,
    }
    c = audit["checks"]
    problems = []
    if c["observed_quorum_meets_file_claim_of_3"] is False: problems.append("reachable nodes report a quorum below the 3 the file claims (2 of 4 is not Byzantine tolerant)")
    if len(c["nodes_exposing_pbft_status"]) < len(probes): problems.append("not every listed node exposes a PBFT engine endpoint")
    if c["invariants_with_attached_evidence"] == 0: problems.append("none of the claimed invariants carries any attached evidence")
    if c["endpoints_reachable"].split("/")[0] != str(len(probes)): problems.append("some listed endpoints were unreachable")
    audit["verdict"] = "CLAIMS_NOT_SUPPORTED_BY_LIVE_OBSERVATION" if problems else "NO_CONTRADICTION_FOUND_BY_THESE_CHECKS"
    audit["problems"] = problems
    audit["limits"] = ["a read-only GET audit cannot prove a claim true; it can show a claim is contradicted or unsupported",
                       "the nodes' own status fields are self-reported", "endpoints may change after audited_at; repeat the same GETs to re-check"]
    with open(OUT, "w") as f:
        json.dump(audit, f, indent=2, sort_keys=True)
    print(audit["verdict"]); [print(" -", p) for p in problems]; print(json.dumps(c, indent=1)[:900])


if __name__ == "__main__":
    main()
