#!/usr/bin/env python3
import json, hashlib, sys

ALLOWED_CONTRACTS = {"continuity.v1"}
REQUIRED = {"contract", "provenance", "evidence_ids", "expected_head", "records"}

def validate(doc):
    if not isinstance(doc, dict): return False, "DOCUMENT_TYPE"
    missing = sorted(REQUIRED - set(doc))
    if missing: return False, "MISSING_KEYS:" + ",".join(missing)
    if doc["contract"] not in ALLOWED_CONTRACTS: return False, "UNKNOWN_CONTRACT"
    if doc["provenance"] in (None, "", "INHERITED"): return False, "PROVENANCE_REQUIRED"
    ids = doc["evidence_ids"]
    if not isinstance(ids, list) or not ids: return False, "EVIDENCE_REQUIRED"
    if any(not isinstance(x, int) for x in ids): return False, "EVIDENCE_ID_TYPE"
    if ids != list(range(ids[0], ids[0] + len(ids))): return False, "NON_CONTIGUOUS_IDS"
    records = doc["records"]
    if not isinstance(records, list) or len(records) != len(ids): return False, "RECORD_COUNT"
    if not records or not all(isinstance(r, dict) for r in records): return False, "RECORD_SHAPE"
    actual = records[-1].get("id")
    if actual != doc["expected_head"] or actual != ids[-1]: return False, "HEAD_MISMATCH"
    return True, "OK"

def run(path):
    try:
        with open(path, encoding="utf-8") as f: doc = json.load(f)
        ok, reason = validate(doc)
        print(("PASS " if ok else "REFUSE ") + reason)
        return 0 if ok else 1
    except Exception as e:
        print("REFUSE INPUT_ERROR:" + type(e).__name__)
        return 1

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