"""Standard-library replay of Session 96 capacity witnesses, with no solver.

Checks actual paths, source coordinates, word memberships and anchor equality.
It does not certify UNSAT or interpret any output as plaintext.
"""
from pathlib import Path
import hashlib
import json

ROOT=Path(__file__).resolve().parent
READ=lambda name:json.loads((ROOT/name).read_text())
SHA=lambda name:hashlib.sha256((ROOT/name).read_bytes()).hexdigest()


def verify():
    plan=READ('independent_phrase_next_plan.json')
    spec=READ('independent_phrase_execution.json')
    data=READ('independent_phrase_inputs.json')
    checks=READ('independent_phrase_checks.json')
    result=READ('independent_phrase_results.json')
    assert spec['plan_sha256']==SHA('independent_phrase_next_plan.json')
    assert spec['driver_sha256']==SHA('independent_phrase_capacity.py')
    assert spec['input_sha256']==SHA('independent_phrase_inputs.json')
    assert checks['passed'] and checks['execution_sha256']==SHA('independent_phrase_execution.json')
    assert result['execution_sha256']==SHA('independent_phrase_execution.json')
    assert result['checks_sha256']==SHA('independent_phrase_checks.json')
    for name,expected in plan['input_hashes'].items():assert SHA(name)==expected,name
    assert result['complete'] and result['real_solver_checks']==2 and len(result['rows'])==2
    paired={r['id']:r['formula_sha256'] for r in result['rows']};audits=[]
    for query,row in zip(data['queries'],result['rows']):
        assert query['id']==row['id'] and row['membership_count']==query['constraint_count']
        assert row['sections']==8 and row['cross_section_equalities']==6 and row['timeout_ms']==30000
        assert SHA(row['formula'])==row['formula_sha256']
        manifest=READ(row['manifest'])
        assert manifest['paired_formula_hashes']==paired and manifest['formula_sha256']==row['formula_sha256']
        assert manifest['execution_sha256']==SHA('independent_phrase_execution.json')
        assert manifest['input_sha256']==SHA('independent_phrase_inputs.json')
        assert manifest['checks_sha256']==SHA('independent_phrase_checks.json')
        assert manifest['both_formulas_saved_before_either_check']
        if row['status']!='sat':
            assert row['status'] in ['unsat','unknown']
            audits.append({'id':row['id'],'status':row['status'],'no_capacity_witness':True})
            continue
        witness=row['capacity_witness'];assert len(witness['sections'])==8
        decoded={};keys=[];paths=[];runes=0
        for source,path in zip(query['sections'],witness['sections']):
            assert source['id']==path['section'] and path['initial_phase']==0
            key=path['key'];keys.append(key)
            assert len(key)==13 and all(type(k)==int and 0<=k<29 for k in key)
            masks=path['skipped_F_offsets'];skips=set(masks)
            assert len(masks)==len(skips)
            assert all(type(p)==int and 0<=p<len(source['cipher']) and source['cipher'][p]==0 for p in skips)
            phase=0;plain=[];encoded=[];phases=[]
            for position,current in enumerate(source['cipher']):
                phases.append(phase)
                if position in skips:value=0;encoded.append(value)
                else:
                    value=(current-key[phase])%29;encoded.append((value+key[phase])%29)
                    phase=(phase+1)%13
                plain.append(value)
            assert encoded==source['cipher'] and phase==path['end_phase']
            assert hashlib.sha256(bytes(plain)).hexdigest()==path['full_output_sha256']
            allowed={int(p):set(values) for p,values in source['constraints'].items()}
            assert all(plain[p] in values for p,values in allowed.items())
            assert path['membership_outputs']==[{'offset':p,'value':plain[p]} for p in sorted(allowed)]
            decoded[source['id']]=plain;runes+=len(plain)
            paths.append({'section':source['id'],'runes':len(plain),'F_skips':len(skips),
                'membership_count':len(allowed),'end_phase':phase,'exact_inverse_reencryption':True})
        assert runes==12947 and len(query['couplings'])==len(witness['equalities'])==6
        for pair,record in zip(query['couplings'],witness['equalities']):
            a,b=pair;assert record['endpoints']==pair
            assert decoded[a['section']][a['offset']]==decoded[b['section']][b['offset']]==record['value']
            assert pair[0]['section']==6 and pair[1]['section']==8
        assert [pair[0]['offset'] for pair in query['couplings']]==list(range(28,34))
        assert [pair[1]['offset'] for pair in query['couplings']]==list(range(3310,3316))
        source_by_id={s['id']:s for s in query['sections']}
        assert source_by_id[6]['cipher'][28:34]==source_by_id[8]['cipher'][3310:3316]
        assert source_by_id[6]['cipher'][28:34]==[23,11,1,17,18,10]
        distinct=len({tuple(k) for k in keys});assert distinct==witness['distinct_arrays']
        audits.append({'id':row['id'],'status':'sat','runes_replayed':runes,
            'all_memberships_satisfied':True,'six_output_equalities_verified':True,
            'source_3_3_anchor_coordinates_verified':True,'distinct_arrays':distinct,
            'sections':paths,'not_a_translation':True})
    output={'session':96,'results_sha256':SHA('independent_phrase_results.json'),
        'verifier_sha256':SHA('independent_phrase_verify.py'),'audits':audits,
        'solver_imports_or_calls':0,'no_UNSAT_proof_certificate_checked':True}
    target=ROOT/'independent_phrase_witness_audit.json'
    if target.exists():assert READ(target.name)==output,'Preserve differing audit outcomes.'
    else:target.write_text(json.dumps(output,indent=2)+'\n')
    print(json.dumps({'verified_statuses':[(a['id'],a['status']) for a in audits],
        'SAT_witnesses_replayed':sum(a['status']=='sat' for a in audits),'extra_solver_calls':0}))


if __name__=='__main__':verify()
