#!/usr/bin/env python3
"""OMR — standalone offline auditor. Imports no CAIN code.

Verifies a live operational mission receipt without trusting the colony:
  * the receipt (plan, per-step signature, key scope, epoch, chain, head, Merkle)
  * every attached OMEGA SEAL against the gateway key (Ed25519, published at
    /fabric/omega-seal) and its binding to the step's decision id, verdict and
    blocked flag
  * both live anchors with the shipped Quorum-QaaS verifier
  * nine reconstructible attacks, the two delegated-key forgeries and the two
    seal substitutions shipped in the report
  * the run nonce commitment and every hypothesis

Modes:
  python3 -I verify_omr_offline.py <bundle-dir>
  python3 -I verify_omr_offline.py --receipts <dir>     (cross-host re-check)
"""
import base64
import hashlib
import json
import sys
from pathlib import Path

from cryptography.exceptions import InvalidSignature
from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PublicKey

EX = {"OMR_MANIFEST.json", "OMR_SIGNED_BODY.json", "MERKLE_ROOT.txt", "PUBLICATION.json",
      "OMR_OMEGA_SEAL.json", "OMR_VERIFICATION_RESULTS.json", "OMR_TAMPER_RESULTS.json"}
DOMAIN = "cain42.omega-seal.v1"
A9 = ["truncate_tail", "drop_middle", "reorder_steps", "substitute_step_detail", "flip_verdict",
      "change_decision_id", "replay_step_from_other_mission", "forge_step_signature", "alter_plan_length"]


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


def sha(b):
    return hashlib.sha256(b if isinstance(b, (bytes, bytearray)) else str(b).encode()).hexdigest()


def merkle(items):
    level = sorted(items) if items else ["0" * 64]
    while len(level) > 1:
        if len(level) % 2:
            level.append(level[-1])
        level = [sha(level[i] + level[i + 1]) for i in range(0, len(level), 2)]
    return level[0]


def vsig(pk_hex, sig_hex, body):
    try:
        Ed25519PublicKey.from_public_bytes(bytes.fromhex(pk_hex)).verify(bytes.fromhex(sig_hex), body)
        return True
    except (InvalidSignature, ValueError, KeyError):
        return False


def step_body(s):
    return canon({"mission_id": s["mission_id"], "index": s["index"], "kind": s["kind"],
                  "detail": s["detail"], "prev_hash": s["prev_hash"], "key_id": s["key_id"],
                  "signed_epoch": s["signed_epoch"]})


def close_body(c):
    return canon({k: v for k, v in c.items() if k != "signature"})


def scoped(rec):
    h, steps, close = rec["header"], rec["steps"], rec["close"]
    keys = {k["key_id"]: k for k in h.get("keys", [])}
    root = keys.get(h.get("root_key_id"))
    fails = []
    if not root or root.get("role") != "root":
        fails.append("ROOT")
    elif not vsig(root["pubkey"], h.get("signature", ""), canon({k: v for k, v in h.items() if k != "signature"})):
        fails.append("HEADER_SIG")
    if h.get("plan_hash") != sha(canon(h.get("plan_kinds"))):
        fails.append("PLAN_HASH")
    if h.get("plan_steps") != len(h.get("plan_kinds", [])):
        fails.append("PLAN_COUNT")
    if len(steps) != h.get("plan_steps"):
        fails.append("STEP_COUNT")
    if [s.get("kind") for s in steps] != h.get("plan_kinds"):
        fails.append("PLAN_SEQ")
    prev = h.get("start_head")
    for i, s in enumerate(steps):
        if s.get("index") != i:
            fails.append(f"INDEX@{i}")
        if s.get("mission_id") != h.get("mission_id"):
            fails.append(f"MISSION@{i}")
        if s.get("prev_hash") != prev:
            fails.append(f"CHAIN@{i}")
        if sha(step_body(s)) != s.get("step_hash"):
            fails.append(f"HASH@{i}")
        k = keys.get(s.get("key_id"))
        if not k:
            fails.append(f"KEY@{i}")
        else:
            lo, hi = k.get("scope", [0, 0])
            if k.get("role") not in ("mission", "delegate"):
                fails.append(f"ROLE@{i}")
            if not (lo <= i < hi):
                fails.append(f"SCOPE@{i}")
            if int(s.get("signed_epoch", 10 ** 9)) > int(k.get("expires_epoch", -1)):
                fails.append(f"EPOCH@{i}")
            if not vsig(k["pubkey"], s.get("signature", ""), step_body(s)):
                fails.append(f"SIG@{i}")
        prev = s.get("step_hash")
    if close.get("steps") != len(steps):
        fails.append("CLOSE_COUNT")
    if steps and close.get("head") != steps[-1].get("step_hash"):
        fails.append("HEAD")
    if close.get("merkle_root") != merkle([s["step_hash"] for s in steps]):
        fails.append("MERKLE")
    if not root or not vsig(root["pubkey"], close.get("signature", ""), close_body(close)):
        fails.append("CLOSE_SIG")
    return fails


def naive(rec):
    h, steps = rec["header"], rec["steps"]
    keys = {k["key_id"]: k for k in h.get("keys", [])}
    fails = []
    prev = steps[0]["prev_hash"] if steps else h.get("start_head")
    for i, s in enumerate(steps):
        if s.get("prev_hash") != prev:
            fails.append(f"CHAIN@{i}")
        k = keys.get(s.get("key_id"))
        if not k or not vsig(k["pubkey"], s.get("signature", ""), step_body(s)):
            fails.append(f"SIG@{i}")
        prev = s.get("step_hash")
    return fails


def seal_msg(seal):
    body = {k: v for k, v in seal.items() if k != "signature_b64"}
    return f"{DOMAIN}\x1f{sha(canon(body))}".encode()


def seal_ok(seal, step, keys):
    try:
        pub = base64.b64decode(keys[seal["key_id"]])
        Ed25519PublicKey.from_public_bytes(pub).verify(base64.b64decode(seal["signature_b64"]), seal_msg(seal))
    except (InvalidSignature, KeyError, ValueError, TypeError):
        return False
    ref = step["detail"].get("seal_ref") or {}
    return (seal.get("seal_id") == ref.get("seal_id")
            and seal.get("decision_id") == ref.get("decision_id") == step["detail"].get("decision_id")
            and seal.get("verdict") == ref.get("verdict") == step["detail"].get("verdict")
            and bool(seal.get("blocked")) == bool(step["detail"].get("blocked")))


def operational(rec, seals, keys):
    fails = scoped(rec)
    by_id = {s.get("seal_id"): s for s in seals}
    decide = [s for s in rec["steps"] if s["kind"].startswith("decide_")]
    for i, s in enumerate(decide):
        seal = by_id.get((s["detail"].get("seal_ref") or {}).get("seal_id"))
        if not seal:
            fails.append(f"SEAL_MISSING@{i}")
        elif not seal_ok(seal, s, keys):
            fails.append(f"SEAL_BINDING@{i}")
        if seal and seal.get("authorizes") and (seal.get("verdict") != "ALLOWED" or seal.get("blocked")):
            fails.append(f"SEAL_AUTHORITY@{i}")
    return fails


def attack9(name, rec, other):
    import copy
    r = copy.deepcopy(rec)
    if name == "truncate_tail":
        r["steps"].pop()
    elif name == "drop_middle":
        r["steps"].pop(3)
    elif name == "reorder_steps":
        r["steps"][4:6] = list(reversed(r["steps"][4:6]))
    elif name == "substitute_step_detail":
        r["steps"][1]["detail"]["decision_id"] = "fd_fake"
    elif name == "flip_verdict":
        r["steps"][2]["detail"]["verdict"] = "ALLOWED"
    elif name == "change_decision_id":
        r["steps"][3]["detail"]["decision_id"] = "fd_other"
    elif name == "replay_step_from_other_mission":
        r["steps"][5] = copy.deepcopy(other["steps"][5])
    elif name == "forge_step_signature":
        r["steps"][1]["detail"]["decision_id"] = "fd_forged"
        r["steps"][1]["signature"] = "00" * 64
    elif name == "alter_plan_length":
        r["header"]["plan_kinds"] = r["header"]["plan_kinds"][:-1]
        r["header"]["plan_steps"] -= 1
        r["header"]["plan_hash"] = sha(canon(r["header"]["plan_kinds"]))
    return r


def anchor_ok(anchor, root):
    try:
        sys.path.insert(0, str(Path(__file__).resolve().parent))
        import verify_qaas_receipt as V
    except Exception as e:  # noqa: BLE001
        return False, f"qaas verifier unavailable: {e}"
    out = V.verify_receipt(anchor.get("receipt") or {}, pin=anchor.get("pin"), digest=root)
    return out.get("verdict") == "NOTARIZED", out.get("verdict")


def receipts_mode(d):
    data = json.loads((Path(d) / "OMR_CROSSHOST.json").read_text())
    keys = data["keys"]
    heads, fails, checks = {}, [], 0
    for m in data["missions"]:
        f = operational(m["receipt"], m["seals"], keys)
        checks += 1
        if f:
            fails.append(f"{m['mission']}:{f[:3]}")
        ok, verdict = anchor_ok(m["anchor"], m["receipt"]["close"]["merkle_root"])
        checks += 1
        if not ok:
            fails.append(f"{m['mission']}:anchor:{verdict}")
        heads[m["mission"]] = m["receipt"]["close"]["head"]
    print(json.dumps({"ok": not fails, "checks": checks, "heads": heads, "failures": fails[:5]}))
    return 0 if not fails else 1


def main():
    args = sys.argv[1:]
    if args and args[0] == "--receipts":
        return receipts_mode(args[1])
    d = Path(args[0] if args else ".")
    checks = []

    def ck(n, ok, detail=""):
        checks.append((n, bool(ok), detail))

    man = json.loads((d / "OMR_MANIFEST.json").read_text())
    ck("manifest signature", vsig(man["pubkey_ed25519"], man["signature"],
                                  canon({k: v for k, v in man.items() if k != "signature"})))
    listed = man["files"]
    ck("declared files present", all((d / f).exists() for f in listed))
    ck("file hashes", all(sha((d / f).read_bytes()) == h for f, h in listed.items() if (d / f).exists()))
    ck("merkle root", merkle([sha((d / f).read_bytes()) for f in listed if (d / f).exists()]) == man["merkle_root"])

    pre = json.loads((d / "OMR_PREREGISTRATION.json").read_text())
    frz = json.loads((d / "OMR_PREREGISTRATION_FREEZE.json").read_text())
    ck("preregistration hash", sha((d / "OMR_PREREGISTRATION.json").read_bytes()) == frz["preregistration_sha256"])
    ck("seven hypotheses", len(pre["hypotheses"]) == 7)

    rep = json.loads((d / "OMR_RUN_REPORT.json").read_text())
    keys = rep["seal_keys"]
    ck("no model calls", rep["design"]["model_calls"] == 0)
    ck("two missions", {m["mission"] for m in rep["missions"]} == {"mission1", "mission2"})
    ck("run nonce committed", rep["missions"][0]["receipt"]["header"].get("freeze_nonce_sha256") == frz["nonce_sha256"])

    for m in rep["missions"]:
        name = m["mission"]
        ck(f"{name} receipt verifies", not scoped(m["receipt"]))
        ck(f"{name} operational verifies", not operational(m["receipt"], m["seals"], keys))
        ck(f"{name} six seals bound", len(m["seals"]) == 6 and
           all(seal_ok(s, st, keys) for s, st in zip(m["seals"],
                                                     [x for x in m["receipt"]["steps"] if x["kind"].startswith("decide_")])))
        ok, verdict = anchor_ok(m["anchor"], m["receipt"]["close"]["merkle_root"])
        ck(f"{name} live anchor", ok, str(verdict))
        ck(f"{name} tampered digest rejected",
           (m["anchor"].get("tampered_verify") or {}).get("verdict") != "NOTARIZED")

    for m in rep["missions"]:
        name = m["mission"]
        other = next(x for x in rep["missions"] if x["mission"] != name)["receipt"]
        rej = []
        for a in A9:
            rej.append(bool(operational(attack9(a, m["receipt"], other), m["seals"], keys)))
        ck(f"{name} nine attacks rejected", all(rej), str([a for a, r in zip(A9, rej) if not r]))
        reported = {c["attack"]: c for c in rep["attacks"][name]}
        ck(f"{name} attack table matches", all(reported[a]["operational_rejected"] == r for a, r in zip(A9, rej)))
        for a in ("delegate_out_of_scope", "delegate_after_epoch"):
            fg = rep["forged"][name][a]
            ck(f"{name} {a} rejected", bool(operational(fg, m["seals"], keys)))
            ck(f"{name} {a} fools signature+chain", not naive(fg))
        for a in ("fabricated_seal", "swapped_seal"):
            sl = rep["forged"][name][a]
            ck(f"{name} {a} rejected", bool(operational(m["receipt"], sl, keys)))
            ck(f"{name} {a} fools signature+chain", not naive(m["receipt"]))
        ck(f"{name} naive misses exactly six",
           sorted(c["attack"] for c in rep["attacks"][name] if not c["naive_rejected"]) == sorted([
               "alter_plan_length", "delegate_after_epoch", "delegate_out_of_scope",
               "fabricated_seal", "swapped_seal", "truncate_tail"]))

    ch = rep["cross_host"]
    ck("cross-host ran", ch.get("exit") == 0)
    ck("cross-host machine differs", bool(ch.get("machine_id")))
    ck("cross-host verified", bool((ch.get("result") or {}).get("ok")))
    ck("cross-host heads match",
       (ch.get("result") or {}).get("heads") == {m["mission"]: m["receipt"]["close"]["head"] for m in rep["missions"]})

    h = rep["hypotheses"]
    expect = "OPERATIONAL_MISSION_RECEIPT_SUPPORTED" if all(
        h[k]["verdict"] == "SUPPORTED" for k in ("H1_live_gate_binding", "H2_operational_verifier", "H3_live_anchor",
                                                 "H4_cross_host", "H5_governance", "H6_replication")) else "NOT_SUPPORTED"
    ck("verdict matches hypotheses", rep["verdict"] == expect, rep["verdict"])
    ck("no seal grants authority without an ALLOWED verdict",
       all((not s.get("authorizes")) or (s.get("verdict") == "ALLOWED" and not s.get("blocked"))
           for m in rep["missions"] for s in m["seals"]))
    sp = d / "OMR_OMEGA_SEAL.json"
    if sp.exists():
        seal = json.loads(sp.read_text())
        ck("omega seal bound", seal.get("merkle_root") == man["merkle_root"] and seal.get("verdict") == "ALLOWED",
           seal.get("seal_label", ""))
    else:
        ck("omega seal not yet issued (pre-seal copy)", True, "pre-seal")
    ck("external review recorded", "NOT OBTAINED" in " ".join(rep["limits"]))

    fails = [n for n, ok, _ in checks if not ok]
    for n, ok, detail in checks:
        print(("PASS " if ok else "FAIL ") + n + (f"  [{detail}]" if detail and not ok else ""))
    print(f"{len(checks) - len(fails)}/{len(checks)} checks passed")
    return 0 if not fails else 1


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