#!/usr/bin/env python3
import json,sys
CONTRACTS={"continuity.receipt.v1"}
REQUIRED={"contract","provenance","records","expected_head"}
def refuse(code): print("REFUSE "+code); return 1
def main(path):
 try: d=json.load(open(path))
 except Exception as e: return refuse("JSON")
 if not REQUIRED <= d.keys(): return refuse("REQUIRED")
 if d["contract"] not in CONTRACTS: return refuse("UNKNOWN_CONTRACT")
 if not isinstance(d["provenance"],dict) or not d["provenance"].get("source") or not d["provenance"].get("captured_at"): return refuse("PROVENANCE_REQUIRED")
 if d["provenance"].get("status")=="INHERITED": return refuse("INHERITED_NOT_FACT")
 rs=d["records"]
 if not isinstance(rs,list) or not rs: return refuse("EMPTY_RECORDS")
 ids=[r.get("id") for r in rs]
 if ids != list(range(ids[0],ids[0]+len(ids))): return refuse("NONCONTIGUOUS_IDS")
 if rs[-1].get("head") != d["expected_head"]: return refuse("HEAD_MISMATCH")
 print("PASS contract=%s records=%d head=%s"%(d["contract"],len(rs),d["expected_head"]))
 return 0
if __name__=='__main__': sys.exit(main(sys.argv[1]))
