#!/usr/bin/env python3
"""Standalone verifier for this verification bundle. Imports no CAIN code.

    python3 verify_offline.py [--products DIR]

Checks the bundle's own file hashes, then re-runs the signed-sample verifiers in the
AGENTIC 75 products bundle with the pinned keys recorded here. Reports FAIL on anything
it cannot check: no silent pass.
"""
import argparse, hashlib, json, subprocess, sys
from pathlib import Path

HERE = Path(__file__).resolve().parent
bad = []

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

def check(name, ok, why=""):
    print(("PASS  " if ok else "FAIL  ") + name + (("  -- " + why) if why and not ok else ""))
    if not ok:
        bad.append(name)

m = json.loads((HERE / "MANIFEST.json").read_text())
check("manifest says unsigned", m.get("signed") is False)
for name, spec in (m.get("files") or {}).items():
    p = HERE / name
    check(f"{name} exists", p.is_file())
    if p.is_file():
        check(f"{name} sha256", sha(p) == spec.get("sha256"))

run = json.loads((HERE / "RUN.json").read_text())
check("selftest verified 75", run["selftest"].get("manifests_verified") == 75,
      str(run["selftest"].get("manifests_verified")))
check("offline total is 75", run["offline"].get("total") == 75)
check("offline failures recorded honestly", run["offline"].get("failed") == 75 - run["offline"].get("passed"))

ap = argparse.ArgumentParser()
ap.add_argument("--products", default=str(HERE.parent / "agentic-75-products-2026-11-12"))
a = ap.parse_args()
prod = Path(a.products)
if not prod.is_dir():
    check("products bundle present", False, "pass --products DIR")
else:
    ok = 0
    for row in run["offline"]["results"]:
        s = prod / "deliveries" / row["sku"] / "signed-sample"
        key = (s / "public_key.txt")
        payload = s / row.get("payload", "run.json")
        if not (key.is_file() and payload.is_file()):
            check(f"{row['sku']} signed sample present", False)
            continue
        v = subprocess.run([sys.executable, "verify_offline.py", payload.name,
                            "--pinned-key", key.read_text().strip()],
                           cwd=str(s), capture_output=True, text=True)
        good = v.returncode == 0
        check(f"{row['sku']} re-verifies offline", good, (v.stdout + v.stderr)[-160:])
        ok += 1 if good else 0
    check("all 75 signed samples re-verify", ok == 75, f"{ok}/75")

print()
print(f"{len(bad)} failure(s)")
sys.exit(1 if bad else 0)
