#!/usr/bin/env python3
"""MVC — standalone auditor for the customer-verifier study. Imports no CAIN code.

Checks the manifest, the tool hash and import set, re-runs the shipped
CUSTOMER_VERIFY.py (stdlib only) against the shipped payload, and recomputes the
report's verification results.

Usage: python3 -I verify_mvc_offline.py <bundle-dir>
"""
import ast
import hashlib
import json
import subprocess
import sys
from pathlib import Path

EX = {"MVC_MANIFEST.json", "MVC_SIGNED_BODY.json", "MERKLE_ROOT.txt", "PUBLICATION.json",
      "MVC_OMEGA_SEAL.json", "MVC_VERIFICATION_RESULTS.json", "MVC_TAMPER_RESULTS.json"}
STDLIB = {"base64", "hashlib", "json", "sys", "binascii", "struct", "typing", "pathlib", "os"}


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):
    from cryptography.exceptions import InvalidSignature
    from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PublicKey
    try:
        Ed25519PublicKey.from_public_bytes(bytes.fromhex(pk)).verify(bytes.fromhex(sig), body)
        return True
    except (InvalidSignature, ValueError, KeyError):
        return False


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

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

    man = json.loads((d / "MVC_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"])

    rep = json.loads((d / "MVC_RUN_REPORT.json").read_text())
    src = (d / "CUSTOMER_VERIFY.py").read_text()
    ck("tool hash matches report", sha(src.encode()) == rep["design"]["tool_sha256"])
    tree = ast.parse(src)
    imports = sorted({(n.module or "").split(".")[0] if isinstance(n, ast.ImportFrom) else a.name.split(".")[0]
                      for n in ast.walk(tree)
                      for a in (n.names if isinstance(n, ast.Import) else [])
                      if isinstance(n, (ast.Import, ast.ImportFrom))})
    ck("tool imports stdlib only", all(i in STDLIB for i in imports), str(imports))
    ck("tool has no CAIN import", "import cain" not in src.lower() and "from cain" not in src.lower())
    ck("no model calls", rep["design"]["model_calls"] == 0)
    ck("differential agrees", rep["differential"]["agree"] == rep["differential"]["cases"] == 100)
    ck("all attacks rejected", len(rep["attacks"]) == 24 and all(a["rejected"] for a in rep["attacks"]))
    ck("two tenants", set(rep["clean"]["heads"]) == {"acme", "globex"})

    run = subprocess.run([sys.executable, "-S", "-I", str(d / "CUSTOMER_VERIFY.py"), str(d / "MVC_PAYLOAD.json")],
                         capture_output=True, text=True)
    out = {}
    for line in reversed((run.stdout or "").strip().splitlines()):
        if line.startswith("{"):
            try:
                out = json.loads(line)
                break
            except ValueError:
                continue
    ck("shipped tool verifies the shipped payload", run.returncode == 0 and out.get("ok"),
       (run.stdout + run.stderr)[-300:])
    ck("tool heads match the report", out.get("heads") == rep["clean"]["heads"])
    ck("remote host differs and verified",
       bool(rep["remote"]["machine_id"]) and rep["remote"]["out"].get("ok")
       and rep["remote"]["out"].get("heads") == rep["clean"]["heads"])
    h = rep["hypotheses"]
    expect = "CUSTOMER_VERIFIER_SUPPORTED" if all(
        h[k]["verdict"] == "SUPPORTED" for k in ("H1_differential", "H2_customer_verifies", "H3_stdlib_only",
                                                 "H4_portable", "H5_clean_exit", "H6_replication")) else "NOT_SUPPORTED"
    ck("verdict matches hypotheses", rep["verdict"] == expect, rep["verdict"])
    ck("ordering disclosed", "after" in json.dumps(rep.get("ordering", {})))
    sp = d / "MVC_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())
