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

def digest(obj):
    return hashlib.sha256(json.dumps(obj, sort_keys=True, separators=(',', ':')).encode()).hexdigest()

def consume(validated_head_hash, stable_id, actor, next_gate, current_head_hash, resulting_evidence_ref):
    if current_head_hash != validated_head_hash:
        return {'status':'RESUME_REJECTED','reason':'HEAD_CHANGED','validated_head_hash':validated_head_hash,'current_head_hash':current_head_hash}
    if not all(isinstance(x,str) and x for x in (validated_head_hash, stable_id, actor, next_gate, resulting_evidence_ref)):
        return {'status':'RESUME_REJECTED','reason':'REQUIRED_FIELD_MISSING'}
    receipt={'validated_head_hash':validated_head_hash,'consumed_head_hash':current_head_hash,'stable_id':stable_id,'consumer_or_actor':actor,'resumed_at':'fixture-time','next_gate_consumed':next_gate,'resulting_evidence_ref':resulting_evidence_ref}
    receipt['consumption_id']=digest(receipt)
    return {'status':'RESUME_CONSUMED','receipt':receipt}

cases=[
 ('positive', consume('a'*64,'job-7','terry','apply-next','a'*64,'evidence://job-7/result')),
 ('head-changed', consume('a'*64,'job-7','terry','apply-next','b'*64,'evidence://job-7/result')),
 ('stale-effect', consume('a'*64,'job-7','terry','apply-next','b'*64,'evidence://stale-head-b/result')),
]
for name,result in cases: print(json.dumps({'case':name,**result},sort_keys=True))
