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

ALLOWED_CONTRACTS = {"continuity.receipt.v1"}
REQUIRED = {"contract", "provenance", "work_line", "beneficiary", "current_state", "next_step", "evidence_ids", "expected_head"}

def validate(doc):
    if not isinstance(doc, dict): return False, "document_not_object"
    missing = sorted(REQUIRED - doc.keys())
    if missing: return False, "missing:" + ",".join(missing)
    if doc["contract"] not in ALLOWED_CONTRACTS: return False, "unknown_contract"
    if doc["provenance"] in (None, "", "INHERITED"): return False, "invalid_provenance"
    ids = doc["evidence_ids"]
    if not isinstance(ids, list) or not ids: return False, "empty_evidence_ids"
    if any(not isinstance(x, int) for x in ids): return False, "evidence_ids_not_int"
    if ids != list(range(ids[0], ids[-1] + 1)): return False, "non_contiguous_evidence_ids"
    if doc["expected_head"] != ids[-1]: return False, "head_mismatch"
    return True, "ok"

def main():
    path = sys.argv[1] if len(sys.argv) > 1 else "-"
    raw = sys.stdin.read() if path == "-" else open(path, encoding="utf-8").read()
    try: doc = json.loads(raw)
    except Exception: print("REFUSE invalid_json"); return 1
    ok, reason = validate(doc)
    print(("PASS " if ok else "REFUSE ") + reason)
    return 0 if ok else 1

if __name__ == "__main__": raise SystemExit(main())
