#!/usr/bin/env python3
"""Reference verifier — OKF Attestation Binding Profile 0.1 (draft).
Usage: verify-okf.py <concept.md>
Deps: pip install pyyaml rfc8785 requests
"""
import sys, json, yaml, hashlib, requests

def split_frontmatter(raw: bytes):
    text = raw.decode("utf-8")
    assert text.startswith("---\n"), "no frontmatter"
    fm, body = text[4:].split("\n---\n", 1)
    return yaml.safe_load(fm), body

def canonical_hash(fm: dict, body: str) -> str:
    import rfc8785
    fm = {k: v for k, v in fm.items() if k != "rubric_attestation"}
    jcs = rfc8785.dumps(fm)  # bytes
    body_b = body.replace("\r\n", "\n").encode("utf-8")
    h = hashlib.sha3_256()
    h.update(jcs); h.update(b"\x00"); h.update(body_b)
    return h.hexdigest()

def main(path):
    raw = open(path, "rb").read()
    fm, body = split_frontmatter(raw)
    ra = fm.get("rubric_attestation")
    if not ra:
        print("UNBOUND: no rubric_attestation key"); sys.exit(2)
    local = canonical_hash(fm, body)
    if local != ra["content_hash"]:
        print(f"HASH-MISMATCH\n local:  {local}\n bound:  {ra['content_hash']}")
        sys.exit(1)
    r = requests.get(ra["verify_url"], timeout=15)
    r.raise_for_status()
    v = r.json()
    # TODO: offline path — fed pubkeys + HCS mirror check (see verify-apa.py)
    if v.get("valid") is True:
        print(f"BOUND-VERIFIED  {ra['attestation_id']}  hcs_seq={ra['anchor'].get('hcs_seq')}")
        sys.exit(0)
    print("UNRESOLVABLE:", json.dumps(v)[:200]); sys.exit(3)

if __name__ == "__main__":
    main(sys.argv[1])
