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

Verifies a two-party mission ledger without trusting the operator:
  * the operator signature, the declared count, the entry chain, head and Merkle root
  * each entry's inner mission receipt (plan, per-step signature, chain, head)
  * each entry's customer acknowledgement under the customer key, and its binding
  * completeness: the set of entries equals the set of the customer's acks
  * both live anchors with the shipped Quorum-QaaS verifier
  * twelve attacks, nine of them reconstructible here (three need the operator key)
  * every hypothesis, the verdict and the seal

Modes:
  python3 -I verify_mlr_offline.py <bundle-dir>
  python3 -I verify_mlr_offline.py --receipts <dir>
"""
import hashlib
import json
import sys
from pathlib import Path

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

EX = {"MLR_MANIFEST.json", "MLR_SIGNED_BODY.json", "MERKLE_ROOT.txt", "PUBLICATION.json",
      "MLR_OMEGA_SEAL.json", "MLR_VERIFICATION_RESULTS.json", "MLR_TAMPER_RESULTS.json"}


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, sig, body):
    try:
        Ed25519PublicKey.from_public_bytes(bytes.fromhex(pk)).verify(bytes.fromhex(sig), body)
        return True
    except (InvalidSignature, ValueError, KeyError):
        return False


def receipt_fails(rec):
    h, steps, close = rec["header"], rec["steps"], rec["close"]
    fails = []
    if not vsig(h.get("pubkey", ""), h.get("signature", ""), canon({k: v for k, v in h.items() if k != "signature"})):
        fails.append("HDR")
    if h.get("plan_hash") != sha(canon(h.get("plan_kinds"))):
        fails.append("PLAN_HASH")
    if len(steps) != h.get("plan_steps"):
        fails.append("COUNT")
    if [s.get("kind") for s in steps] != h.get("plan_kinds"):
        fails.append("SEQ")
    prev = h.get("start_head")
    for i, s in enumerate(steps):
        if s.get("index") != i or s.get("prev_hash") != prev:
            fails.append(f"CHAIN@{i}")
        body = canon({"mission_id": s["mission_id"], "index": s["index"], "kind": s["kind"],
                      "detail": s["detail"], "prev_hash": s["prev_hash"]})
        if sha(body) != s.get("step_hash") or not vsig(h["pubkey"], s["signature"], body):
            fails.append(f"STEP@{i}")
        prev = s.get("step_hash")
    if steps and close.get("head") != steps[-1]["step_hash"]:
        fails.append("HEAD")
    if close.get("merkle_root") != merkle([s["step_hash"] for s in steps]):
        fails.append("MERKLE")
    if not vsig(h["pubkey"], close.get("signature", ""), canon({k: v for k, v in close.items() if k != "signature"})):
        fails.append("CLOSE")
    return fails


def entry_hash(e):
    return sha(canon({k: v for k, v in e.items() if k != "entry_hash"}))


def operator_fails(lg):
    fails = []
    if not vsig(lg.get("operator_pubkey", ""), lg.get("signature", ""),
                canon({k: v for k, v in lg.items() if k != "signature"})):
        fails.append("OP_SIG")
    if len(lg["entries"]) != lg.get("declared_missions"):
        fails.append("DECLARED")
    prev = "0" * 64
    for i, e in enumerate(lg["entries"]):
        if e.get("seq") != i or e.get("prev") != prev or entry_hash(e) != e.get("entry_hash"):
            fails.append(f"ENTRY@{i}")
        if receipt_fails(e["receipt"]):
            fails.append(f"RECEIPT@{i}")
        prev = e.get("entry_hash")
    if lg["entries"] and lg.get("head") != lg["entries"][-1]["entry_hash"]:
        fails.append("HEAD")
    if lg.get("merkle_root") != merkle([e["entry_hash"] for e in lg["entries"]]):
        fails.append("MERKLE")
    return fails


def ack_fails(ack, tenant):
    if not ack:
        return ["MISSING"]
    body = {k: v for k, v in ack.items() if k not in ("signature", "customer_pubkey")}
    ok = vsig(ack.get("customer_pubkey", ""), ack.get("signature", ""), canon(body))
    return [] if ok and ack.get("tenant") == tenant else ["ACK"]


def twoparty_fails(lg, acks_all):
    fails = operator_fails(lg)
    tenant = lg["tenant"]
    acks = [a for a in acks_all if a.get("tenant") == tenant]
    by_mission = {a["mission_id"]: a for a in acks}
    if len(acks) != len(by_mission):
        fails.append("ACK_DUP")
    if lg.get("declared_missions") != len(acks):
        fails.append("DECLARED_VS_ACK")
    if len(lg["entries"]) != len(acks):
        fails.append("ENTRIES_VS_ACK")
    seen = set()
    for i, e in enumerate(lg["entries"]):
        a = e.get("ack")
        if ack_fails(a, tenant):
            fails.append(f"ACK_INVALID@{i}")
            continue
        if (a["mission_id"] != e["mission_id"] or a["seq"] != e["seq"]
                or a["receipt_root"] != e["receipt_root"]):
            fails.append(f"ACK_BIND@{i}")
        seen.add(a["mission_id"])
        if a["mission_id"] not in by_mission:
            fails.append(f"ACK_NOT_CUSTOMER@{i}")
    if [m for m in by_mission if m not in seen]:
        fails.append("OMITTED")
    if any(a["mission_id"] not in {e["mission_id"] for e in lg["entries"]} for a in acks):
        fails.append("CUSTOMER_MISSING")
    return fails


def receipts_mode(d):
    data = json.loads((Path(d) / "MLR_CROSSHOST.json").read_text())
    heads, fails, checks = {}, [], 0
    for t in data["tenants"]:
        lg = data["ledgers"][t]
        f = twoparty_fails(lg, data["acks"])
        checks += 1
        if f:
            fails.append(f"{t}:{f[:3]}")
        a = data["anchors"][t]
        ok, v = anchor_ok(a, lg["merkle_root"])
        checks += 1
        if not ok:
            fails.append(f"{t}:anchor:{v}")
        heads[t] = lg["head"]
    print(json.dumps({"ok": not fails, "checks": checks, "heads": heads, "failures": fails[:5]}))
    return 0 if not fails else 1


def anchor_ok(a, 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 unavailable: {e}"
    out = V.verify_receipt(a.get("receipt") or {}, pin=a.get("pin"), digest=root)
    return out.get("verdict") == "NOTARIZED", out.get("verdict")


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 / "MLR_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 / "MLR_PREREGISTRATION.json").read_text())
    frz = json.loads((d / "MLR_PREREGISTRATION_FREEZE.json").read_text())
    ck("preregistration hash", sha((d / "MLR_PREREGISTRATION.json").read_bytes()) == frz["preregistration_sha256"])
    salts = json.loads((d / "SALTS.json").read_text())
    ck("salt commitments", all(sha(v.encode()) == frz["salt_commitments"][k] for k, v in salts.items()))
    ck("seven hypotheses", len(pre["hypotheses"]) == 7)

    rep = json.loads((d / "MLR_RUN_REPORT.json").read_text())
    ck("no model calls", rep["design"]["model_calls"] == 0)
    ck("two tenants", set(rep["ledgers"]) == {"acme", "globex"})
    for t, lg in rep["ledgers"].items():
        ck(f"{t} ledger verifies", not twoparty_fails(lg, rep["acks"]),
           str(twoparty_fails(lg, rep["acks"])[:4]))
        ck(f"{t} inner receipts", not any(receipt_fails(e["receipt"]) for e in lg["entries"]))
        ck(f"{t} three acks", len([a for a in rep["acks"] if a["tenant"] == t]) == 3)
        ok, v = anchor_ok(rep["anchors"][t], lg["merkle_root"])
        ck(f"{t} anchor", ok, str(v))
        ck(f"{t} tampered digest rejected",
           (rep["anchors"][t].get("tampered_verify") or {}).get("verdict") != "NOTARIZED")
        reported = {c["attack"]: c for c in rep["attacks"][t]}
        ck(f"{t} two-party rejects all", all(c["twoparty_rejected"] for c in rep["attacks"][t]))
        ck(f"{t} attack table matches",
           all(reported[k]["operator_rejected"] == c["operator_rejected"]
               for k, c in zip(reported, rep["attacks"][t])))
    core = {"drop_middle_mission", "drop_tail_and_redeclare", "reorder_missions",
            "substitute_mission", "invent_unacked_mission"}
    ck("operator-only blind to the five rewrites",
       all(core <= {c["attack"] for c in rep["attacks"][t] if not c["operator_rejected"]}
           for t in rep["ledgers"]))
    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") == {t: lg["head"] for t, lg in rep["ledgers"].items()})
    h = rep["hypotheses"]
    expect = "TWO_PARTY_LEDGER_SUPPORTED" if all(
        h[k]["verdict"] == "SUPPORTED" for k in ("H1_two_party_completeness", "H2_attack_suite", "H3_live_anchor",
                                                 "H4_cross_host", "H5_governance", "H6_replication")) else "NOT_SUPPORTED"
    ck("verdict matches hypotheses", rep["verdict"] == expect, rep["verdict"])
    sp = d / "MLR_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())
