"""Session 94: fixed greedy membership reduction of the 81-word contradiction.

Delete memberships, never ciphertext. Reuse the unchanged Boolean solver.
Run prepare, controls, scan. No retries, second pass or adopted exceptions.
"""
from pathlib import Path
import argparse
import hashlib
import json

import z3
import boolean_shared_capacity as boolean
from lp_core import R, LET

old=boolean.old
ROOT=old.ROOT
PLAN=ROOT/'shared_core_next_plan.json'
INPUT=ROOT/'shared_core_inputs.json'
SPEC=ROOT/'shared_core_execution.json'
CONTROLS=ROOT/'shared_core_controls.json'
LOG=ROOT/'shared_core_scan_log.json'
WORDS=ROOT/'shared_core_final_words.json'
AUDITS=ROOT/'shared_core_countermodels.json'
RESULTS=ROOT/'shared_core_results.json'
FORMULA=ROOT/'shared_core_final.smt2'
SEED=330192
SCAN_TIMEOUT=5000
FINAL_TIMEOUT=30000
DEPENDENCIES=['shared_core_next_plan.json','boolean_shared_capacity.py',
    'boolean_shared_execution.json','boolean_shared_controls.json','boolean_shared_results.json',
    'boolean_shared_AIO_all_singletons.smt2','boolean_shared_AIO_all_singletons.manifest.json',
    'boolean_shared_AIO_prior_red_exemptions.smt2','boolean_shared_AIO_prior_red_exemptions.manifest.json',
    'shared_periodic_cases.json','liber-primus__transcription--master.txt']


def active_hash(values):
    return hashlib.sha256(json.dumps(values,separators=(',',':')).encode()).hexdigest()


def clone_sections(sections):
    return [{'id':s['id'],'cipher':s['cipher'].copy(),
             'constraints':{int(p):list(v) for p,v in s['constraints'].items()}} for s in sections]


def verify_archives():
    boolean.verify();prior=old.read(boolean.RESULTS);checks=old.read(boolean.CONTROLS)
    assert prior['complete'] and len(prior['rows'])==2 and all(r['status']=='unsat' for r in prior['rows'])
    assert prior['execution_sha256']==old.sha(boolean.SPEC)==checks['execution_sha256']
    assert prior['controls_sha256']==old.sha(boolean.CONTROLS) and checks['passed']
    paired={r['id']:r['formula_sha256'] for r in prior['rows']}
    for row in prior['rows']:
        manifest=old.read(ROOT/row['manifest'])
        assert old.sha(ROOT/row['formula'])==row['formula_sha256']==manifest['formula_sha256']
        assert manifest['paired_formula_hashes']==paired
        assert manifest['execution_sha256']==old.sha(boolean.SPEC)


def prepare():
    assert not CONTROLS.exists() and not LOG.exists() and not RESULTS.exists(),'Preserve recorded work.'
    verify_archives();saved=old.read(old.CASES)
    query=next(q for q in saved['queries'] if q['id']=='AIO_prior_red_exemptions')
    words=[]
    for section in saved['real_section_layout']:
        selected=next(s for s in query['sections'] if s['id']==section['id'])
        offsets=set(old.constraints(selected))
        for word in section['singletons']:
            if word['local_offset'] not in offsets:continue
            assert not word['prior_red_exemption']
            words.append({**word,'section':section['id'],
                'id':f"s{section['id']}_r{word['local_offset']}",
                'cipher_rune':R[word['cipher_value']],
                'cipher_label':LET[word['cipher_value']]})
    words.sort(key=lambda w:w['global_offset'])
    assert len(words)==81 and len({w['global_offset'] for w in words})==81
    derivatives=[]
    for case in saved['toy_cases']:
        sections=clone_sections(case['sections']);positions=sorted(sections[0]['constraints'])
        fs=[p for p in positions if sections[0]['cipher'][p]==0];deleted=(fs or positions)[0]
        del sections[0]['constraints'][deleted]
        assert all(a['cipher']==b['cipher'] for a,b in zip(sections,case['sections']))
        derivatives.append({'field':case['field'],'period':case['period'],'case':case['case'],
            'deleted_first_sequence_position':deleted,
            'deleted_constraint_at_cipher_F':sections[0]['cipher'][deleted]==0,'sections':sections})
    fixture=[{'id':0,'cipher':[1,2,1,2,1,2],'constraints':{i:[1] for i in range(6)}},
             {'id':1,'cipher':[1,0,2,1,2,1],'constraints':{i:[1] for i in [0,1,2]}}]
    old.dump(INPUT,{'session':94,'base_query':query,'ordered_words':words,
             'toy_deletions':derivatives,'explicit_F_fixture':fixture,
             'all_eight_full_streams_preserved':True})
    old.dump(SPEC,{'session':94,'saved_before_controls_and_scan':True,
        'driver_sha256':old.sha(Path(__file__)),'input_sha256':old.sha(INPUT),
        'input_hashes':{name:old.sha(ROOT/name) for name in DEPENDENCIES},
        'z3_version':z3.get_full_version(),'solver_seed':SEED,
        'scan_timeout_ms':SCAN_TIMEOUT,'final_timeout_ms':FINAL_TIMEOUT,
        'ordered_global_offsets':[w['global_offset'] for w in words],
        'deletion_rule':'Membership dictionary entry removed; all original ciphertext arrays retained.',
        'max_real_solver_checks':82,'one_scan_no_retries':True,
        'membership_omissions_not_adopted_exceptions':True})
    print('PREPARED 81 ordered words, 96 toy deletion policies and 4 explicit F cases',flush=True)


def verify():
    spec=old.read(SPEC)
    assert spec['driver_sha256']==old.sha(Path(__file__)) and spec['input_sha256']==old.sha(INPUT)
    for name,sha in spec['input_hashes'].items():assert old.sha(ROOT/name)==sha,name
    assert spec['z3_version']==z3.get_full_version()
    verify_archives()


def run_check(sections,period,field=29,permit=True,timeout=SCAN_TIMEOUT):
    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 controls():
    verify();assert not CONTROLS.exists(),'Do not overwrite recorded controls.'
    data=old.read(INPUT);rows=[]
    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:
            w=answer['capacity_witness'];key=tuple(w['key']);assert key in expected
            assert all(s['initial_phase'] in expected[key][i] for i,s in enumerate(w['sections']))
        rows.append({k:v for k,v in case.items() if k!='sections'}|
            {'selective_F':permit,'brute_compatible_keys':len(expected),'exact_agreement':True,'solver':answer})
    explicit=[]
    for deleted in (False,True):
      for permit in (False,True):
        sections=clone_sections(data['explicit_F_fixture'])
        if deleted:del sections[1]['constraints'][1]
        assert sections[1]['cipher']==[1,0,2,1,2,1]
        expected,_=old.brute_sections(sections,2,3,permit)
        target='sat' if deleted and permit else 'unsat'
        assert ('sat' if expected else 'unsat')==target
        answer=run_check(sections,2,3,permit);assert answer['status']==target
        if target=='sat':
            assert answer['capacity_witness']['key']==[0,1]
            assert 1 in answer['capacity_witness']['sections'][1]['skipped_F_offsets']
        explicit.append({'membership_deleted':deleted,'selective_F':permit,
                         'expected_status':target,'physical_F_preserved':True,'solver':answer})
    old.dump(CONTROLS,{'session':94,'execution_sha256':old.sha(SPEC),'passed':True,
        'toy_policy_comparisons':rows,'explicit_F_cases':explicit,
        'archived_session93_source_inputs_controls_and_formulas_verified':True,
        'no_real_queries_run':True})
    print('CONTROLS PASS: 96 deletion comparisons and 4 physical-F cases',flush=True)


def project(data,active):
    permitted=set(active);by_section={s['id']:{} for s in data['base_query']['sections']}
    for w in data['ordered_words']:
        if w['global_offset'] in permitted:by_section[w['section']][w['local_offset']]=[3,10,24]
    sections=[{'id':s['id'],'cipher':s['cipher'],'constraints':by_section[s['id']]}
              for s in data['base_query']['sections']]
    assert len(sections)==8 and sum(len(s['cipher']) for s in sections)==12947
    assert sum(len(s['constraints']) for s in sections)==len(active)
    return sections


def audit_countermodel(data,words,row):
    witness=row['solver']['capacity_witness'];key=witness['key'];decoded={}
    for section,w in zip(data['base_query']['sections'],witness['sections']):
        assert section['id']==w['section']
        phase=w['initial_phase'];skips=set(w['skipped_F_offsets']);plain=[]
        for i,current in enumerate(section['cipher']):
            if i in skips:
                assert current==0;plain.append(0)
            else:
                p=(current-key[phase])%29
                assert (p+key[phase])%29==current
                plain.append(p);phase=(phase+1)%13
        assert phase==w['end_phase'] and old.digest(plain)==w['full_output_sha256']
        decoded[section['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,'scan_step':row['step'],
            'all_other_final_memberships_satisfied':True,'omitted_word_value':value,
            'omitted_word_label':LET[value],'omitted_word_membership_violated':True,
            'full_stream_inverse_reencryption':True,'witness_location':'shared_core_scan_log.json, matching scan step',
            'not_a_translation':True}


def scan():
    verify();control=old.read(CONTROLS)
    assert control['passed'] and control['execution_sha256']==old.sha(SPEC)
    assert not LOG.exists() and not RESULTS.exists(),'Preserve existing attempts; no reruns.'
    data=old.read(INPUT);active=[w['global_offset'] for w in data['ordered_words']];rows=[]
    for step,word in enumerate(data['ordered_words'],1):
        identity=word['global_offset'];assert identity in active
        before=active.copy();candidate=[p for p in active if p!=identity]
        answer=run_check(project(data,candidate),13)
        removed=answer['status']=='unsat'
        if removed:active=candidate
        row={'step':step,'word':word,'active_before':before,
             'candidate_active':candidate,'candidate_active_sha256':active_hash(candidate),
             'solver':answer,'removed_membership':removed,'active_after':active.copy()}
        rows.append(row)
        old.dump(LOG,{'session':94,'scan_complete':False,'execution_sha256':old.sha(SPEC),
            'rows':rows,'active_global_offsets':active})
        print('STEP',step,'/81',word['id'],answer['status'],
              'removed' if removed else 'kept','active',len(active),flush=True)
    old.dump(LOG,{'session':94,'scan_complete':True,'execution_sha256':old.sha(SPEC),
         'rows':rows,'active_global_offsets':active,'scan_solver_checks':81})
    retained=[w for w in data['ordered_words'] if w['global_offset'] in set(active)]
    old.dump(WORDS,{'session':94,'execution_sha256':old.sha(SPEC),'words':retained,
         'active_global_offsets':active,'active_sha256':active_hash(active),
         'all_physical_runes_preserved':True,'not_adopted_word_exceptions':True})
    final_instance=boolean.build(project(data,active),13)
    final_instance['solver'].set(timeout=FINAL_TIMEOUT,random_seed=SEED)
    FORMULA.write_text(final_instance['solver'].to_smt2())
    old.dump(FORMULA.with_suffix('.manifest.json'),{'session':94,'formula':FORMULA.name,
         'formula_sha256':old.sha(FORMULA),'execution_sha256':old.sha(SPEC),
         'scan_log_sha256':old.sha(LOG),'final_words_sha256':old.sha(WORDS),
         'saved_before_final_solver_check':True,'timeout_ms':FINAL_TIMEOUT,'solver_seed':SEED})
    final=boolean.check(final_instance);final['query_timeout_ms']=FINAL_TIMEOUT
    audits=[]
    for row in rows:
        if row['solver']['status']=='sat':
            assert row['word']['global_offset'] in active
            audits.append(audit_countermodel(data,retained,row))
    old.dump(AUDITS,{'session':94,'scan_log_sha256':old.sha(LOG),'final_words_sha256':old.sha(WORDS),
         'audits':audits,'no_extra_solver_checks':True})
    statuses={s:sum(r['solver']['status']==s for r in rows) for s in ['sat','unsat','unknown']}
    assert len(retained)==statuses['sat']+statuses['unknown']
    irreducible=final['status']=='unsat' and len(audits)==len(retained)
    verify()
    old.dump(RESULTS,{'session':94,'complete':True,'execution_sha256':old.sha(SPEC),
         'controls_sha256':old.sha(CONTROLS),'scan_log_sha256':old.sha(LOG),
         'final_words_sha256':old.sha(WORDS),'countermodel_audits_sha256':old.sha(AUDITS),
         'final_formula_sha256':old.sha(FORMULA),'initial_constraints':81,
         'final_constraints':len(retained),'deletion_status_counts':statuses,'final_check':final,
         'inclusion_minimal_verified':irreducible,'minimum_cardinality_proved':False,
         'retained_words_without_SAT_deletion_witness':[
             w['id'] for w in retained if not any(a['global_offset']==w['global_offset'] for a in audits)],
         'real_solver_checks':82,'one_pass_completed':True,'no_adopted_extra_exceptions':True,
         'no_language_score_or_new_plaintext':True})
    print('COMPLETE',json.dumps({'remaining':len(retained),'statuses':statuses,
        'final_status':final['status'],'inclusion_minimal':irreducible}),flush=True)


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