#!/usr/bin/env python3
"""OSPP conformance runner: checks any passport verifier against the official ospp.v1 vectors. Python 3.10+, standard library only.

    python3 ospp_conformance.py [--vectors ospp-v1-vectors.json | URL] [--report report.json] -- <your verifier command ...>

The verifier is run once per passport vector as

    <your verifier command ...> <file.ospp> --json [--trusted-issuer=<key id>[,<key id>...]]

and must print JSON with a "rules" list of {"rule": "V-01", "result": "VALID" | "INVALID" | "UNDETERMINED" | "NOT_APPLICABLE"} (the shape both
reference verifiers print). Its exit code is not judged. The implementation conforms when every rule of every vector matches the expected
result. The report records the vectors' version and SHA-256, every case, and the outcome; attach it when you list an implementation.

Examples:  python3 ospp_conformance.py -- ospp-verify                       (the Python reference verifier)
           python3 ospp_conformance.py -- node ospp-verify.mjs              (the TypeScript reference verifier)
           python3 ospp_conformance.py -- ./my-verifier --mode=cli         (yours)"""
from __future__ import annotations
import argparse, datetime as dt, hashlib, json, os, platform, subprocess, sys, tempfile, urllib.request

DEFAULT_VECTORS = "https://www.ospp.it.com/build/downloads/ospp-v1-vectors.json"

def load(src: str) -> bytes:
    if src.startswith(("https://", "http://")):
        with urllib.request.urlopen(src, timeout=60) as r: return r.read()
    with open(src, "rb") as f: return f.read()

def cases(v: dict) -> list[tuple[str, dict, list[str], dict]]:
    out = [(p["name"], p["bundle"], [], p["expected"]) for p in v["passports"]]
    pc = v.get("pinned_issuer_case")
    if pc:
        pb = v["passports"][pc["passport_index"]]
        out.append((pb["name"] + " [issuer pinned]", pb["bundle"], list(pc["trusted_issuer_key_ids"]), {**pb["expected"], "V-04": pc["expected_V04"]}))
    return out

def run_case(cmd: list[str], bundle: dict, trusted: list[str], timeout: int) -> dict:
    with tempfile.TemporaryDirectory() as td:
        path = os.path.join(td, "passport.ospp")
        with open(path, "w", encoding="utf-8") as f: json.dump(bundle, f, ensure_ascii=False)
        args = cmd + [path, "--json"] + ([f"--trusted-issuer={','.join(trusted)}"] if trusted else [])
        r = subprocess.run(args, capture_output=True, text=True, timeout=timeout)
    try: data = json.loads(r.stdout)
    except ValueError: raise RuntimeError(f"no JSON on stdout (exit {r.returncode}): {(r.stderr or r.stdout).strip()[:300]}")
    rules = data.get("rules") if isinstance(data, dict) else None
    if not isinstance(rules, list): raise RuntimeError('the JSON has no "rules" list')
    return {str(x.get("rule")): str(x.get("result")) for x in rules if isinstance(x, dict)}

def main() -> int:
    ap = argparse.ArgumentParser(description="Check an OSPP passport verifier against the official vectors.", usage="%(prog)s [--vectors SRC] [--report FILE] -- <verifier command ...>")
    ap.add_argument("--vectors", default=DEFAULT_VECTORS, help="the core vectors file or its URL (default: the published one)")
    ap.add_argument("--report", help="write a JSON report here")
    ap.add_argument("--timeout", type=int, default=60, help="seconds per case")
    argv = sys.argv[1:]
    if "--" not in argv: ap.print_usage(); print("give the verifier command after --", file=sys.stderr); return 2
    k = argv.index("--"); ns = ap.parse_args(argv[:k]); cmd = argv[k + 1:]
    if not cmd: print("give the verifier command after --", file=sys.stderr); return 2
    raw = load(ns.vectors); v = json.loads(raw); sha = hashlib.sha256(raw).hexdigest()
    print(f"vectors {v.get('vector_version')} ({v.get('protocol_version')}), sha256 {sha[:16]}…  verifier: {' '.join(cmd)}")
    results = []; failed = 0
    for name, bundle, trusted, expected in cases(v):
        try:
            got = run_case(cmd, bundle, trusted, ns.timeout)
            diff = {r: {"expected": e, "got": got.get(r, "missing")} for r, e in sorted(expected.items()) if got.get(r) != e}
            ok = not diff; err = None
        except Exception as e:
            ok, diff, err = False, {}, str(e)
        failed += not ok
        results.append({"case": name, "pass": ok, **({"differences": diff} if diff else {}), **({"error": err} if err else {})})
        print(f"{'pass' if ok else 'FAIL'}  {name}" + (f"\n      {err}" if err else "") + "".join(f"\n      {r}: expected {d['expected']}, got {d['got']}" for r, d in diff.items()))
    summary = {"runner": "ospp_conformance.py 1", "vectors": {"source": ns.vectors, "sha256": sha, "vector_version": v.get("vector_version"), "protocol_version": v.get("protocol_version"),
               "verification_revision": v.get("verification_revision")}, "verifier_command": cmd, "cases": len(results), "passed": len(results) - failed, "failed": failed,
               "conformant": failed == 0, "ran_at": dt.datetime.now(dt.timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ"), "platform": platform.platform(), "results": results}
    if ns.report:
        with open(ns.report, "w", encoding="utf-8") as f: json.dump(summary, f, indent=1)
    print(f"\n{len(results) - failed} of {len(results)} cases pass: " + ("CONFORMANT" if failed == 0 else "NOT CONFORMANT"))
    return 0 if failed == 0 else 1

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