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

KNOWN_CONTRACT = "1f916.inbox.since_last_visit.v3"
KNOWN_MODE = "id"

def gate(packet):
    if packet.get("contract") != KNOWN_CONTRACT or packet.get("cursor_mode") != KNOWN_MODE:
        return {"status":"UNKNOWN", "reason":"unknown contract or mode"}
    ack = packet.get("ack_cursor")
    offer = packet.get("offered_ack_cursor")
    if ack is None:
        return {"status":"INAPPLICABLE", "reason":"no ACK submitted"}
    if not isinstance(ack, dict) or not isinstance(offer, dict):
        return {"status":"REFUSED", "reason":"malformed cursor"}
    if ack != offer:
        return {"status":"REFUSED", "reason":"submitted ACK differs from page-local offer"}
    return {"status":"CONSISTENT_BUT_NOT_PROCESSING_PROOF", "reason":"exact wire offer match; processing provenance absent"}

def main():
    fixtures = [
      ("singleton_exact", {"contract":KNOWN_CONTRACT,"cursor_mode":"id","offered_ack_cursor":{"version":1,"timestamp":100,"comments":5,"mentions":7},"ack_cursor":{"version":1,"timestamp":100,"comments":5,"mentions":7}}, "CONSISTENT_BUT_NOT_PROCESSING_PROOF"),
      ("no_ack", {"contract":KNOWN_CONTRACT,"cursor_mode":"id","offered_ack_cursor":{"version":1}}, "INAPPLICABLE"),
      ("altered_ack", {"contract":KNOWN_CONTRACT,"cursor_mode":"id","offered_ack_cursor":{"version":1,"comments":5},"ack_cursor":{"version":1,"comments":6}}, "REFUSED"),
      ("unknown_contract", {"contract":"future","cursor_mode":"id","ack_cursor":{}}, "UNKNOWN"),
      ("legacy_mode", {"contract":KNOWN_CONTRACT,"cursor_mode":"legacy","ack_cursor":{}}, "UNKNOWN"),
    ]
    out=[]
    for name, packet, expected in fixtures:
        got=gate(packet)
        ok=got["status"] == expected
        out.append({"fixture":name,"expected":expected,"got":got["status"],"pass":ok})
    print(json.dumps({"fixtures":out,"all_pass":all(x["pass"] for x in out)}, indent=2))
    return 0 if all(x["pass"] for x in out) else 1

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