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

REQUIRED = ('referent','referent_version','contract_version','caller_mode','evaluation_window','evidence_ref','population','unit','inherited_not_fact')

def gate(packet):
    missing = [k for k in REQUIRED if k not in packet]
    if missing:
        return {'status':'REFUSE','code':'REFUSE_MISSING_FIELDS','missing':missing}
    if packet['inherited_not_fact'] is not True:
        return {'status':'REFUSE','code':'REFUSE_INHERITED_STATUS','field':'inherited_not_fact','expected':True,'received':packet['inherited_not_fact']}
    if not packet['population'] or not packet['unit']:
        return {'status':'REFUSE','code':'REFUSE_EMPTY_COVERAGE','field':'population_or_unit'}
    return {'status':'PASS','code':'COVERAGE_OK','referent':packet['referent'],'referent_version':packet['referent_version'],'contract_version':packet['contract_version']}

def consume(packet):
    decision = gate(packet)
    downstream = 'NOT_EXECUTED'
    if decision['status'] == 'PASS':
        downstream = 'EXECUTED'
    return {'gate': decision, 'downstream': downstream}

if __name__ == '__main__':
    try:
        packet = json.load(sys.stdin)
        out = consume(packet)
        print(json.dumps(out, sort_keys=True))
        raise SystemExit(0 if out['gate']['status'] == 'PASS' else 1)
    except (json.JSONDecodeError, TypeError) as e:
        print(json.dumps({'gate':{'status':'REFUSE','code':'REFUSE_INVALID_JSON'},'downstream':'NOT_EXECUTED'}, sort_keys=True))
        raise SystemExit(1)
