"""Replay Session 95's 37 necessity witnesses using Python's standard library.

No SAT solver is imported or called. This checks the feasible deletions only;
the final UNSAT decision remains a recorded Z3 result, not a checked proof.
"""
from pathlib import Path
import hashlib
import json

ROOT=Path(__file__).resolve().parent
BUNDLE=ROOT/'shared_completion_witness_bundle.json'


def read(path):return json.loads(path.read_text())
def sha(path):return hashlib.sha256(path.read_bytes()).hexdigest()


def verify():
    bundle=read(BUNDLE)
    for name,expected in bundle['input_hashes'].items():assert sha(ROOT/name)==expected,name
    data=read(ROOT/'shared_completion_inputs.json')
    words=read(ROOT/'shared_completion_final_words.json')['words']
    results=read(ROOT/'shared_completion_results.json')
    archived=read(ROOT/'shared_core_scan_log.json')['rows']
    by_global={w['global_offset']:w for w in words}
    assert len(words)==len(by_global)==37
    assert len(data['base_query']['sections'])==8
    assert sum(len(s['cipher']) for s in data['base_query']['sections'])==12947
    expected={w['global_offset']:w for w in data['words']}
    assert all(expected[offset]==word for offset,word in by_global.items())
    covered=set();runes=0
    for case in bundle['cases']:
        word=case['word'];offset=word['global_offset'];witness=case['capacity_witness']
        assert offset in by_global and word==by_global[offset] and offset not in covered
        original=archived[case['session94_scan_step']-1]
        assert original['word']==word and original['solver']['status']=='sat'
        assert original['solver']['capacity_witness']==witness
        assert set(by_global)-{offset}<=set(original['candidate_active'])
        key=witness['key'];assert len(key)==13 and all(type(k)==int and 0<=k<29 for k in key)
        assert len(witness['sections'])==8
        decoded={}
        for number,(section,path) in enumerate(zip(data['base_query']['sections'],witness['sections'])):
            assert section['id']==path['section'] and 0<=path['initial_phase']<13
            if number==0:assert path['initial_phase']==0
            phase=path['initial_phase'];skips=set(path['skipped_F_offsets'])
            assert len(skips)==len(path['skipped_F_offsets'])
            assert all(type(p)==int and 0<=p<len(section['cipher']) and section['cipher'][p]==0 for p in skips)
            output=[];inverse=[]
            for position,current in enumerate(section['cipher']):
                if position in skips:value=0;inverse.append(value)
                else:
                    value=(current-key[phase])%29;inverse.append((value+key[phase])%29)
                    phase=(phase+1)%13
                output.append(value)
            assert inverse==section['cipher'] and phase==path['end_phase']
            assert hashlib.sha256(bytes(output)).hexdigest()==path['full_output_sha256']
            decoded[section['id']]=output;runes+=len(output)
        for other_offset,other in by_global.items():
            value=decoded[other['section']][other['local_offset']]
            assert (value not in {3,10,24}) if other_offset==offset else (value in {3,10,24})
        covered.add(offset)
    assert covered==set(by_global)
    assert results['final_check']['status']=='unsat' and results['inclusion_minimal_verified']
    print(json.dumps({'necessity_witnesses_verified':len(covered),'runes_replayed':runes,
        'all_full_streams_reencrypted':True,'solver_imports_or_calls':0,
        'UNSAT_proof_independently_checked':False,'source':'recorded final UNSAT plus checked feasible deletions'}))


if __name__=='__main__':verify()
