#!/usr/bin/env python3
"""Standalone verifier for the E144 exploratory organism bundle.

  python3 -I verify_e144_exploratory.py <bundle_dir>

Checks the SHA-256 file manifest, Merkle root and Ed25519 signature, then runs the two study verifiers
(which recompute every summary from raw rows). Imports no CAIN code.
"""
from __future__ import annotations

import hashlib
import json
import subprocess
import sys
from pathlib import Path

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

R = []


def check(ok, name, det=""):
    R.append((bool(ok), name, det))


def canon(o) -> str:
    return json.dumps(o, sort_keys=True, separators=(",", ":"), default=float, ensure_ascii=True)


def sha(p: Path) -> str:
    h = hashlib.sha256()
    with p.open("rb") as f:
        for c in iter(lambda: f.read(1 << 16), b""):
            h.update(c)
    return h.hexdigest()


def merkle(leaves):
    if not leaves:
        return hashlib.sha256(b"").hexdigest()
    level = [hashlib.sha256(b"\x00" + bytes.fromhex(h)).digest() for h in leaves]
    while len(level) > 1:
        level = [hashlib.sha256(b"\x01" + level[i] + level[i + 1]).digest() if i + 1 < len(level) else level[i]
                 for i in range(0, len(level), 2)]
    return level[0].hex()


def main() -> int:
    b = Path(sys.argv[1] if len(sys.argv) > 1 else Path(__file__).resolve().parent)
    man = json.loads((b / "MANIFEST.json").read_text())
    pub = man["evidence_pubkey"]
    bad = [f for f, h in man["files"].items() if not (b / f).exists() or sha(b / f) != h]
    check(not bad, "manifest_file_hashes", f"{len(man['files'])} files, mismatched {bad[:5]}")
    root = merkle([man["files"][k] for k in sorted(man["files"])])
    check(root == man["merkle_root"] == (b / "MERKLE_ROOT.txt").read_text().strip(), "merkle_root", root)
    body = {k: man[k] for k in sorted(man) if k != "signature"}
    try:
        Ed25519PublicKey.from_public_bytes(bytes.fromhex(pub)).verify(bytes.fromhex(man["signature"]), canon(body).encode())
        ok = True
    except Exception:
        ok = False
    check(ok, "manifest_signature", pub[:16])
    check("exploratory" in man.get("scope", "") and "not the confirmatory" in man.get("scope", ""), "scope_label", man.get("scope", ""))
    for script, expect in (("verify_e144_organism.py", "10/10"), ("verify_e144_math.py", "6/6")):
        r = subprocess.run([sys.executable, "-I", str(b / script), str(b)], capture_output=True, text=True, timeout=600)
        check(r.returncode == 0 and expect in r.stdout, f"study verifier {script}", (r.stdout.strip().splitlines() or [""])[-1])
    for okk, name, det in R:
        print(("PASS " if okk else "FAIL ") + name + (f"  [{det}]" if det else ""))
    n = sum(1 for x in R if x[0])
    print(f"\n{n}/{len(R)} checks passed; {len(R) - n} failed")
    return 0 if n == len(R) else 1


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