"""Session 95: two fixed final-set deletions, followed by one final check.

Reuse unchanged Boolean mathematics and preserve every historical attempt.
Stages: prepare, checks, run. No retries or extra real solver calls.
"""
from pathlib import Path
import argparse
import hashlib
import json

import z3
import shared_core_audit as core
from lp_core import LET

boolean=core.boolean
old=core.old
ROOT=core.ROOT
PLAN=ROOT/'shared_core_completion_next_plan.json'
INPUT=ROOT/'shared_completion_inputs.json'
SPEC=ROOT/'shared_completion_execution.json'
CHECKS=ROOT/'shared_completion_checks.json'
LOG=ROOT/'shared_completion_log.json'
WORDS=ROOT/'shared_completion_final_words.json'
AUDITS=ROOT/'shared_completion_countermodels.json'
RESULTS=ROOT/'shared_completion_results.json'
SEED=330192
TIMEOUT=30000


def scalar_audit(data,words,row):
    witness=row['solver']['capacity_witness'];key=witness['key'];decoded={}
    assert len(key)==13 and all(type(k)==int and 0<=k<29 for k in key)
    assert len(witness['sections'])==8
    for si,(source,path) in enumerate(zip(data['base_query']['sections'],witness['sections'])):
        assert source['id']==path['section'] and 0<=path['initial_phase']<13
        if si==0:assert path['initial_phase']==0
        phase=path['initial_phase'];masks=path['skipped_F_offsets'];skips=set(masks)
        assert len(masks)==len(skips)
        assert all(0<=p<len(source['cipher']) and source['cipher'][p]==0 for p in skips)
        plain=[];encoded=[]
        for position,cipher in enumerate(source['cipher']):
            if position in skips:
                value=0;encoded.append(value)
            else:
                value=(cipher-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']
        decoded[source['id']]=plain
    omitted=row['word']['global_offset']
    assert all(decoded[w['section']][w['local_offset']] in {3,10,24}
               for w in words if w['global_offset']!=omitted)
    word=row['word'];value=decoded[word['section']][word['local_offset']]
    assert value not in {3,10,24}
    return {'word_id':word['id'],'global_offset':omitted,
        'all_other_final_memberships_satisfied':True,'omitted_word_value':value,
        'omitted_word_label':LET[value],'omitted_word_membership_violated':True,
        'all_eight_full_streams_reencrypted':True,'legal_F_masks_and_phases':True,
        'saved_output_hashes_match':True,'not_a_translation':True}


def verify94():
    core.verify();old.verify();plan=old.read(PLAN)
    for name,expected in plan['input_hashes'].items():assert old.sha(ROOT/name)==expected,name
    result=old.read(core.RESULTS);words=old.read(core.WORDS);log=old.read(core.LOG)
    data=old.read(core.INPUT);controls=old.read(core.CONTROLS);audits=old.read(core.AUDITS)
    assert result['complete'] and result['final_check']['status']=='unsat'
    assert len(words['words'])==result['final_constraints']==39
    for field,name in [('execution_sha256',core.SPEC),('controls_sha256',core.CONTROLS),
       ('scan_log_sha256',core.LOG),('final_words_sha256',core.WORDS),
       ('countermodel_audits_sha256',core.AUDITS),('final_formula_sha256',core.FORMULA)]:
        assert result[field]==old.sha(name)
    manifest=old.read(core.FORMULA.with_suffix('.manifest.json'))
    assert manifest['formula_sha256']==old.sha(core.FORMULA)
    assert manifest['scan_log_sha256']==old.sha(core.LOG)
    assert manifest['final_words_sha256']==old.sha(core.WORDS)
    assert manifest['execution_sha256']==old.sha(core.SPEC)
    active=[w['global_offset'] for w in data['ordered_words']];sat=[]
    assert len(log['rows'])==81 and active==sorted(active)
    for step,row in enumerate(log['rows'],1):
        assert row['step']==step and row['word']==data['ordered_words'][step-1]
        assert row['active_before']==active
        candidate=[p for p in active if p!=row['word']['global_offset']]
        assert row['candidate_active']==candidate and row['candidate_active_sha256']==core.active_hash(candidate)
        assert row['removed_membership']==(row['solver']['status']=='unsat')
        if row['removed_membership']:active=candidate
        assert row['active_after']==active and row['solver']['query_timeout_ms']==5000
        if row['solver']['status']=='sat':sat.append(row)
    assert active==log['active_global_offsets']==words['active_global_offsets']
    assert words['active_sha256']==core.active_hash(active)
    assert len(sat)==len(audits['audits'])==37
    for row in sat:scalar_audit(data,words['words'],row)
    assert controls['passed'] and len(controls['toy_policy_comparisons'])==96
    assert all(r['exact_agreement'] for r in controls['toy_policy_comparisons'])
    assert len(controls['explicit_F_cases'])==4
    assert all(r['solver']['status']==r['expected_status'] for r in controls['explicit_F_cases'])
    assert [w['id'] for w in plan['ordered_targets']]==['s6_r36','s8_r136']
    assert result['retained_words_without_SAT_deletion_witness']==['s6_r36','s8_r136']
    assert len(data['base_query']['sections'])==8
    assert sum(len(s['cipher']) for s in data['base_query']['sections'])==12947
    return data,words['words'],sat


def prepare():
    assert not SPEC.exists() and not CHECKS.exists() and not LOG.exists() and not RESULTS.exists()
    data,words,_=verify94()
    old.dump(INPUT,{'session':95,'base_query':data['base_query'],'words':words,'ordered_words':words,
        'ordered_targets':old.read(PLAN)['ordered_targets'],
        'toy_deletions':data['toy_deletions'],'explicit_F_fixture':data['explicit_F_fixture']})
    old.dump(SPEC,{'session':95,'saved_before_checks_and_real_queries':True,
        'driver_sha256':old.sha(Path(__file__)),'input_sha256':old.sha(INPUT),
        'plan_sha256':old.sha(PLAN),'z3_version':z3.get_full_version(),
        'solver_seed':SEED,'timeout_ms':TIMEOUT,'max_real_solver_checks':3,
        'target_order':['s6_r36','s8_r136'],'one_attempt_per_target':True,
        'Boolean_builder_unchanged':True,'historical_results_preserved':True})
    print('PREPARED final 39-word set and two fixed targets',flush=True)


def verify():
    spec=old.read(SPEC)
    assert spec['driver_sha256']==old.sha(Path(__file__))
    assert spec['input_sha256']==old.sha(INPUT) and spec['plan_sha256']==old.sha(PLAN)
    assert spec['z3_version']==z3.get_full_version()
    verify94()


def run_check(sections,period,field=29,permit=True):
    instance=boolean.build(sections,period,field,permit)
    instance['solver'].set(timeout=TIMEOUT,random_seed=SEED)
    answer=boolean.check(instance);answer['query_timeout_ms']=TIMEOUT
    return answer


def checks():
    verify();assert not CHECKS.exists()
    data=old.read(INPUT);rows=[];explicit=[]
    for case in data['toy_deletions']:
      for permit in (False,True):
        expected,_=old.brute_sections(case['sections'],case['period'],case['field'],permit)
        answer=run_check(case['sections'],case['period'],case['field'],permit)
        assert answer['status']==('sat' if expected else 'unsat')
        if expected:
            witness=answer['capacity_witness'];key=tuple(witness['key']);assert key in expected
            assert all(w['initial_phase'] in expected[key][i] for i,w in enumerate(witness['sections']))
        rows.append({'field':case['field'],'period':case['period'],'case':case['case'],
            'selective_F':permit,'exact_agreement':True,'solver':answer})
    for deleted in (False,True):
      for permit in (False,True):
        sections=core.clone_sections(data['explicit_F_fixture'])
        if deleted:del sections[1]['constraints'][1]
        expected,_=old.brute_sections(sections,2,3,permit)
        target='sat' if deleted and permit else 'unsat'
        answer=run_check(sections,2,3,permit)
        assert ('sat' if expected else 'unsat')==answer['status']==target
        assert sections[1]['cipher']==[1,0,2,1,2,1]
        if target=='sat':assert 1 in answer['capacity_witness']['sections'][1]['skipped_F_offsets']
        explicit.append({'membership_deleted':deleted,'selective_F':permit,
                         'expected_status':target,'solver':answer})
    old.dump(CHECKS,{'session':95,'execution_sha256':old.sha(SPEC),'passed':True,
        'archived_81_step_trace_and_37_witnesses_verified':True,
        'all_inherited_hashes_and_final_provenance_verified':True,
        'toy_policy_comparisons':rows,'explicit_F_cases':explicit,'real_solver_checks':0})
    print('CHECKS PASS: archives, 37 witnesses, 96 fresh enumeration comparisons, four F cases',flush=True)


def save_formula(instance,identity,active,prior_rows):
    formula=ROOT/f'shared_completion_{identity}.smt2'
    assert not formula.exists()
    formula.write_text(instance['solver'].to_smt2())
    manifest=formula.with_suffix('.manifest.json')
    old.dump(manifest,{'session':95,'query':identity,'formula':formula.name,
        'formula_sha256':old.sha(formula),'execution_sha256':old.sha(SPEC),
        'input_sha256':old.sha(INPUT),'checks_sha256':old.sha(CHECKS),
        'active_global_offsets':active,'active_sha256':core.active_hash(active),
        'previous_deletion_results':prior_rows,
        'all_eight_full_streams_preserved':True,'saved_before_this_solver_check':True,
        'timeout_ms':TIMEOUT,'solver_seed':SEED})
    return {'formula':formula.name,'formula_sha256':old.sha(formula),'manifest':manifest.name}


def run():
    verify();assert old.read(CHECKS)['passed'] and not LOG.exists() and not RESULTS.exists()
    assert old.read(CHECKS)['execution_sha256']==old.sha(SPEC)
    data=old.read(INPUT);active=[w['global_offset'] for w in data['words']];rows=[]
    for step,word in enumerate(data['ordered_targets'],1):
        before=active.copy();candidate=[p for p in active if p!=word['global_offset']]
        assert len(candidate)==len(active)-1
        instance=boolean.build(core.project(data,candidate),13)
        instance['solver'].set(timeout=TIMEOUT,random_seed=SEED)
        files=save_formula(instance,word['id'],candidate,[{'word_id':r['word']['id'],'status':r['solver']['status']} for r in rows])
        answer=boolean.check(instance);answer['query_timeout_ms']=TIMEOUT
        if answer['status']=='unsat':active=candidate
        row={'step':step,'word':word,'active_before':before,'candidate_active':candidate,
             'active_after':active.copy(),**files,'solver':answer}
        rows.append(row)
        old.dump(LOG,{'session':95,'complete':False,'execution_sha256':old.sha(SPEC),'rows':rows})
        print('TARGET',word['id'],answer['status'],'remaining',len(active),flush=True)
    old.dump(LOG,{'session':95,'complete':True,'execution_sha256':old.sha(SPEC),'rows':rows})
    retained=[w for w in data['words'] if w['global_offset'] in active]
    old.dump(WORDS,{'session':95,'words':retained,'active_global_offsets':active,
        'active_sha256':core.active_hash(active),'all_physical_runes_preserved':True,
        'membership_omissions_not_adopted_exceptions':True,'execution_sha256':old.sha(SPEC)})
    instance=boolean.build(core.project(data,active),13)
    instance['solver'].set(timeout=TIMEOUT,random_seed=SEED)
    files=save_formula(instance,'final',active,[{'word_id':r['word']['id'],'status':r['solver']['status']} for r in rows])
    final=boolean.check(instance);final['query_timeout_ms']=TIMEOUT
    archived=old.read(core.LOG)['rows'];audited=[]
    for origin,records in [('Session 94',archived),('Session 95',rows)]:
      for row in records:
        if row['solver']['status']=='sat' and row['word']['global_offset'] in active:
            audited.append(scalar_audit(data,retained,row)|{'origin':origin,'step':row['step']})
    old.dump(AUDITS,{'session':95,'audits':audited,'final_words_sha256':old.sha(WORDS),
        'session94_log_sha256':old.sha(core.LOG),'session95_log_sha256':old.sha(LOG),
        'extra_solver_checks':0})
    unresolved=[w['id'] for w in retained if not any(a['global_offset']==w['global_offset'] for a in audited)]
    verify()
    old.dump(RESULTS,{'session':95,'complete':True,'initial_constraints':39,
        'final_constraints':len(retained),'target_outcomes':[
            {'word_id':r['word']['id'],'status':r['solver']['status']} for r in rows],
        'final_check':final,'final_formula':files,
        'verified_deletion_countermodels':len(audited),'unresolved_retained_words':unresolved,
        'inclusion_minimal_verified':final['status']=='unsat' and not unresolved,
        'minimum_cardinality_proved':False,'real_solver_checks':3,
        'execution_sha256':old.sha(SPEC),'checks_sha256':old.sha(CHECKS),
        'log_sha256':old.sha(LOG),'final_words_sha256':old.sha(WORDS),
        'countermodels_sha256':old.sha(AUDITS),'historical_unknowns_unchanged':True,
        'no_new_plaintext_or_adopted_exceptions':True})
    print('COMPLETE',json.dumps({'remaining':len(retained),'final_status':final['status'],
        'verified_countermodels':len(audited),'unresolved':unresolved}),flush=True)


if __name__=='__main__':
    parser=argparse.ArgumentParser();parser.add_argument('stage',choices=['prepare','checks','run'])
    globals()[parser.parse_args().stage]()
