#!/usr/bin/env python3
"""E323 standalone verifier — stdlib + cryptography, imports no CAIN code."""
import hashlib
import json
import sys
from pathlib import Path

S = "AGI: NOT ESTABLISHED · RSI: EXPERIMENTAL"
ENG = {"attest.py", "prereg.py", "run.py", "world.py", "oracles.py", "enumerate.py", "covers.py", "identify.py"}


def canon(o):
    return json.dumps(o, sort_keys=True, separators=(",", ":"), ensure_ascii=False).encode()


def sha(b):
    return hashlib.sha256(b).hexdigest()


def merkle(paths):
    leaves = sorted(sha(p.read_bytes()) for p in paths)
    if not leaves:
        return sha(b"")
    while len(leaves) > 1:
        if len(leaves) % 2:
            leaves.append(leaves[-1])
        leaves = [sha((leaves[i] + leaves[i + 1]).encode()) for i in range(0, len(leaves), 2)]
    return leaves[0]


def completeness(rows):
    keys = ("page_cx", "page_fr", "page_hf", "snap_cx", "snap_fr", "snap_hf",
            "block_cainstudio", "block_mcpgate", "block_clawx", "block_hf", "under_mark")
    return all(all(r[k] for k in keys) for r in rows)


def seals_ok(rows):
    return all(r["claim_seal"] and r["claim_seal"] == r["snapshot_seal"]
               and r["seal_verdict"] == "ALLOWED" and bool(r["snapshot_verdict"]) for r in rows)


def order_ok(rows):
    by = sorted(rows, key=lambda r: r["generated_at"] or "", reverse=True)
    out = {}
    for home in ("cainstudio", "mcpgate", "clawx", "huggingface"):
        pos = [r["positions"][home] for r in rows]
        if any(p < 0 for p in pos):
            out[home] = False
        else:
            act = [r["evolution"] for r in sorted(rows, key=lambda r: r["positions"][home])]
            out[home] = act == [r["evolution"] for r in by]
    return out


def injected(rows):
    import copy
    out = []

    def check(name, mutate, pred):
        r2 = copy.deepcopy(rows)
        mutate(r2)
        out.append({"case": name, "detected": not pred(r2)})

    check("drop_page", lambda r: r[0].__setitem__("page_hf", False), completeness)
    check("drop_block", lambda r: r[0].__setitem__("block_mcpgate", False), completeness)
    check("drop_under_mark", lambda r: r[0].__setitem__("under_mark", False), completeness)
    check("bad_seal", lambda r: r[0].__setitem__("claim_seal", "OMEGA-000000000"), seals_ok)
    def swap(r):
        r[0]["generated_at"], r[1]["generated_at"] = r[1]["generated_at"], r[0]["generated_at"]
    check("swap_order", swap, lambda r: all(order_ok(r).values()))
    check("wrong_snapshot_seal", lambda r: r[0].__setitem__("snapshot_seal", "OMEGA-000000000"), seals_ok)
    return out


def main():
    B = Path(sys.argv[1] if len(sys.argv) > 1 else ".")
    c = []

    def ck(n, ok, d=""):
        c.append({"check": n, "ok": bool(ok), "detail": str(d)[:300]})

    man = json.loads((B / "E323_MANIFEST.json").read_text())
    ck("status", man.get("status") == S)
    ck("label", man.get("label") in ("SURFACE_INTEGRITY_ATTESTED", "DEFECTS_FOUND"))
    body = {k: v for k, v in man.items() if k != "signature"}
    try:
        from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PublicKey
        Ed25519PublicKey.from_public_bytes(bytes.fromhex(man["pubkey_ed25519"])).verify(
            bytes.fromhex(man["signature"]), canon(body))
        ck("signature", True)
    except Exception as ex:  # noqa: BLE001
        ck("signature", False, ex)
    files = man.get("files", {})
    ck("files", all((B / k).exists() for k in files))
    ck("hashes", not [k for k, h in files.items() if (B / k).exists() and sha((B / k).read_bytes()) != h])
    ck("merkle", merkle(sorted(B / k for k in files if (B / k).exists())) == man.get("merkle_root"))
    present = {str(x.relative_to(B)) for x in B.rglob("*") if x.is_file() and "__pycache__" not in x.parts}
    extra = {"E323_MANIFEST.json", "E323_SIGNED_BODY.json", "E323_VERIFICATION_RESULTS.json", "MANIFEST.json",
             "MERKLE_ROOT.txt", "PUBLICATION.json", "E323_OMEGA_SEAL.json", "E323_TAMPER_RESULTS.json"}
    ck("no unlisted", not (present - set(files) - extra), sorted(present - set(files) - extra)[:5])
    ck("code withheld", not any((B / n).exists() for n in ENG))
    pre = json.loads((B / "E323_PREREGISTRATION.json").read_text())
    frz = json.loads((B / "E323_PREREGISTRATION_FREEZE.json").read_text())
    rep = json.loads((B / "E323_RUN_REPORT.json").read_text())
    att = json.loads((B / "E323_SURFACE_ATTESTATION.json").read_text())
    ck("prereg hash", sha((B / "E323_PREREGISTRATION.json").read_bytes()) == frz["preregistration_sha256"])
    ck("freeze before run", frz["frozen_at"] <= rep["generated_at"])
    ck("external not faked", json.loads((B / "E323_EXTERNAL_REVIEW_STATUS.json").read_text()).get("status") == "NOT_OBTAINED")
    ck("deviation disclosed", any(x.get("id") == "D1" and x.get("results_retained") is False for x in pre.get("deviations", [])))
    rows = att["rows"]
    ck("claim set", len(rows) == 17 and all(r["claim"].startswith("C-E3") for r in rows))
    ck("rows complete", all(all(k in r for k in ("page_cx", "page_fr", "page_hf", "snap_cx", "snap_fr", "snap_hf",
                                                  "block_cainstudio", "block_mcpgate", "block_clawx", "block_hf",
                                                  "under_mark", "positions", "claim_seal", "snapshot_seal",
                                                  "seal_verdict", "snapshot_verdict", "generated_at")) for r in rows))
    c1, c2 = completeness(rows), seals_ok(rows)
    o = order_ok(rows)
    meta = att["meta"]
    inj = injected(rows)
    ck("H1 recompute", att["hypotheses"]["H1_completeness"] == ("SUPPORTED" if c1 else "NOT_SUPPORTED"))
    ck("H2 recompute", att["hypotheses"]["H2_seal_parity"] == ("SUPPORTED" if c2 else "NOT_SUPPORTED"))
    ck("H3 recompute", att["hypotheses"]["H3_top_order"] == ("SUPPORTED" if all(o.values()) else "NOT_SUPPORTED"))
    ck("H3 by home", rep["hypotheses"]["H3_top_order"]["by_home"] == o)
    ck("H4 recompute", att["hypotheses"]["H4_index_catalog"] == (
        "SUPPORTED" if meta["index_identical"] and meta["catalog_ok"] else "NOT_SUPPORTED"))
    ck("H5 recompute", att["hypotheses"]["H5_ip_guard"] == ("SUPPORTED" if meta["ip_ok"] else "NOT_SUPPORTED"))
    b6 = rep["hypotheses"]["H6_bundle_reverify"]["bundles"]
    ck("H6 recompute", att["hypotheses"]["H6_bundle_reverify"] == (
        "SUPPORTED" if all(v["pass"] for v in b6) else "NOT_SUPPORTED"))
    ck("H7 recompute", all(i["detected"] for i in inj) and att["hypotheses"]["H7_injected_defects"] == "SUPPORTED")
    req_ok = c1 and c2 and all(o.values()) and meta["index_identical"] and meta["catalog_ok"] and meta["ip_ok"] and \
        all(v["pass"] for v in b6) and all(i["detected"] for i in inj)
    verdict = "SURFACE_INTEGRITY_ATTESTED" if req_ok else "DEFECTS_FOUND"
    ck("verdict", verdict == att["verdict"] == rep["verdict"] == man["label"], f"{verdict} vs {att['verdict']}")
    cnt = att["counts"]
    ck("counts", cnt["claims"] == 17 and cnt["pages"] == 17 and cnt["blocks"] == 17 and cnt["seals"] == 17
       and cnt["injected"] == 6 and cnt["injected_detected"] == 6)
    hd = man.get("headline", {})
    ck("headline", hd.get("claims") == 17 and hd.get("pages") == 17 and hd.get("blocks") == 17
       and hd.get("seals") == 17 and hd.get("injected") == 6 and hd.get("order_ok") == all(o.values()))
    passed = sum(1 for x in c if x["ok"])
    print(json.dumps({"schema": "cain42.e323.verify.v1", "checks": len(c), "passed": passed,
                      "failed": [x for x in c if not x["ok"]], "verdict": verdict}, ensure_ascii=False))
    return 0 if passed == len(c) else 1


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