"""Worked policy models, not product tests. Python 3.10+, standard library only.
Run: python worked_models.py results
"""
import itertools, hashlib, csv, json, sys
from pathlib import Path
FIELDS=('signature_valid','appraisal_ok','fresh','workload_allowed','configuration_allowed','resource_allowed','tenant_match','recipient_bound','policy_current','not_revoked')
DEPS=('source','model','isa_semantics','checker','test_harness','scope')
def h(s): return hashlib.sha256(s.encode()).hexdigest()
def release(c, fields): return all(c.get(k) is True for k in fields)
def bound_gate(current,record):
    return record.get('status')=='pass' and all(k in current and record.get('bindings',{}).get(k)==h(current[k]) for k in DEPS)
def recovery(c,strict):
    return c.get('signature_valid') is True and (not strict or (c.get('approved') is True and c.get('revoked') is False and c.get('version_allowed') is True))
def save(path,rows):
    with path.open('w',newline='',encoding='utf-8') as f:
        w=csv.DictWriter(f,fieldnames=list(rows[0]));w.writeheader();w.writerows(rows)
def run(folder):
    folder=Path(folder);folder.mkdir(parents=True,exist_ok=True)
    rows=[]
    for bits in itertools.product((False,True),repeat=10):
        c=dict(zip(FIELDS,bits)); expected=all(bits)
        for name,fields in [('attestation_only',FIELDS[:3]),('eight_conditions',FIELDS[:8]),('full_contract',FIELDS)]:
            actual=release(c,fields)
            rows.append(dict(case=''.join(str(int(b)) for b in bits),policy=name,released=actual,unauthorized=actual and not expected))
    base={k:'initial-'+k for k in DEPS};rec={'status':'pass','bindings':{k:h(v) for k,v in base.items()}}
    ar=[]
    for bits in itertools.product((False,True),repeat=6):
        cur={k:base[k]+('-changed' if b else '') for k,b in zip(DEPS,bits)}
        for name,result in [('status_only',True),('digest_bound',bound_gate(cur,rec))]:
            ar.append(dict(case=''.join(str(int(b)) for b in bits),gate=name,accepted=result,stale_accepted=result and any(bits)))
    rr=[]
    for bits in itertools.product((False,True),repeat=5):
        c=dict(zip(('signature_valid','approved','revoked','version_allowed','bootable'),bits))
        authorized=c['signature_valid'] and c['approved'] and not c['revoked'] and c['version_allowed']
        for name,strict in [('signature_only',False),('policy_bound',True)]:
            accepted=recovery(c,strict);booted=accepted and c['bootable']
            rr.append(dict(case=''.join(str(int(b)) for b in bits),policy=name,accepted=accepted,booted=booted,unauthorized_boot=booted and not authorized))
    tests=[('missing_claim_denied',not release({},FIELDS)),('non_boolean_true_denied',not release({'fresh':'true'},('fresh',))),('full_contract_accepts_once',sum(r['released'] for r in rows if r['policy']=='full_contract')==1),('full_contract_no_unauthorized',not any(r['unauthorized'] for r in rows if r['policy']=='full_contract')),('unchanged_evidence_accepted',bound_gate(base,rec)),('failed_evidence_denied',not bound_gate(base,dict(rec,status='fail'))),('missing_bindings_denied',not bound_gate(base,{'status':'pass'})),('mapped_mutations_detected',not any(r['stale_accepted'] for r in ar if r['gate']=='digest_bound')),('unmapped_change_invisible_documented_limit',bound_gate(dict(base,unmapped_configuration='changed'),rec)),('strict_recovery_no_unauthorized_boot',not any(r['unauthorized_boot'] for r in rr if r['policy']=='policy_bound'))]
    assert all(ok for name,ok in tests)
    summary={'evidence_status':'synthetic_models_not_deployment_rates','release':{p:{'accepted':sum(r['released'] for r in rows if r['policy']==p),'unauthorized':sum(r['unauthorized'] for r in rows if r['policy']==p)} for p in ('attestation_only','eight_conditions','full_contract')},'assurance':{p:{'accepted':sum(r['accepted'] for r in ar if r['gate']==p),'stale_accepted':sum(r['stale_accepted'] for r in ar if r['gate']==p)} for p in ('status_only','digest_bound')},'recovery':{p:{'accepted':sum(r['accepted'] for r in rr if r['policy']==p),'booted':sum(r['booted'] for r in rr if r['policy']==p),'unauthorized_boot':sum(r['unauthorized_boot'] for r in rr if r['policy']==p)} for p in ('signature_only','policy_bound')},'self_checks_passed':len(tests)}
    save(folder/'release_cases.csv',rows);save(folder/'assurance_cases.csv',ar);save(folder/'recovery_cases.csv',rr);save(folder/'self_checks.csv',[{'test':name,'passed':ok} for name,ok in tests]);(folder/'summary.json').write_text(json.dumps(summary,indent=2))
    return summary
if __name__=='__main__':run(sys.argv[1] if len(sys.argv)>1 else 'results')
