"""Session 93: Boolean expansion of the unchanged shared-key capacity problem.

Python, NumPy, z3-solver. Reuse Session 92 inputs exactly. Run prepare,
controls, then screen. No modular integer arithmetic enters the SMT formula.
"""
from pathlib import Path
import argparse
import itertools
import json
import time

import z3
import shared_periodic_capacity as old

ROOT=old.ROOT
PLAN=ROOT/'boolean_shared_capacity_next_plan.json'
SPEC=ROOT/'boolean_shared_execution.json'
CONTROLS=ROOT/'boolean_shared_controls.json'
RESULTS=ROOT/'boolean_shared_results.json'
SEED=330192
TIMEOUT=30000
INPUTS=['boolean_shared_capacity_next_plan.json','shared_periodic_cases.json',
        'shared_periodic_capacity.py','shared_periodic_execution.json',
        'shared_periodic_controls.json','shared_periodic_results.json',
        'solved_mechanism_audit.py','lp_core.py','word_core.py','lexical_words.py',
        'liber-primus__transcription--master.txt']


def exactly_one(solver,variables):
    solver.add(z3.Or(*variables))
    for a,b in itertools.combinations(variables,2):solver.add(z3.Or(z3.Not(a),z3.Not(b)))


def selected(model,variables):
    choices=[i for i,v in enumerate(variables) if z3.is_true(model.eval(v,model_completion=True))]
    assert len(choices)==1
    return choices[0]


def boolean_ast_check(solver):
    stack=list(solver.assertions());seen=set()
    while stack:
        node=stack.pop();identity=node.get_id()
        if identity in seen:continue
        seen.add(identity);assert node.sort().kind()==z3.Z3_BOOL_SORT
        stack.extend(node.children())
    return len(seen)


def build(sections,period,field=29,permit=True):
    solver=z3.Solver();solver.set(timeout=TIMEOUT,random_seed=SEED)
    keys=[[z3.Bool(f'key_{slot}_{value}') for value in range(field)] for slot in range(period)]
    for slot in keys:exactly_one(solver,slot)
    chains=[]
    for si,section in enumerate(sections):
        cipher=section['cipher'];memberships=old.constraints(section);positions=sorted(memberships)
        initial=[z3.Bool(f's{si}_initial_{h}') for h in range(period)]
        exactly_one(solver,initial)
        if si==0:solver.add(initial[0])
        groups=[];intervals=[];limits=[]
        for j,position in enumerate(positions):
            allowed=memberships[position]
            states=[(h,False,z3.Bool(f's{si}_at{j}_normal_{h}')) for h in range(period)]
            if permit and cipher[position]==0 and 0 in allowed:
                states += [(h,True,z3.Bool(f's{si}_at{j}_skip_{h}')) for h in range(period)]
            exactly_one(solver,[v for h,skip,v in states])
            required={(cipher[position]-p)%field for p in allowed}
            for h,skip,v in states:
                if not skip:solver.add(z3.Or(z3.Not(v),z3.Or(*[keys[h][k] for k in sorted(required)])))
            previous=positions[j-1] if j else -1
            available=[i for i in range(previous+1,position) if cipher[i]==0]
            limit=min(len(available),period-1) if permit else 0
            if j:
                delta=position-previous
                predecessors=[(h,int(skip),v) for h,skip,v in groups[-1]]
            else:
                delta=position
                predecessors=[(h,0,v) for h,v in enumerate(initial)]
            for h,skipped_predecessor,v in predecessors:
                phases={(h+delta-skipped_predecessor-r)%period for r in range(limit+1)}
                compatible=[u for next_h,next_skip,u in states if next_h in phases]
                solver.add(z3.Or(z3.Not(v),z3.Or(*compatible)))
            groups.append(states);intervals.append(available);limits.append(limit)
        chains.append({'initial':initial,'positions':positions,'states':groups,
                       'intervals':intervals,'limits':limits})
    nodes=boolean_ast_check(solver)
    return {'solver':solver,'keys':keys,'chains':chains,'sections':sections,
            'period':period,'field':field,'permit':permit,
            'assertion_count':len(solver.assertions()),'unique_boolean_ast_nodes':nodes}


def check(instance):
    solver=instance['solver'];start=time.monotonic();result=solver.check();elapsed=time.monotonic()-start
    out={'status':str(result),'solver_seconds':round(elapsed,6),
         'constraints':sum(len(old.constraints(s)) for s in instance['sections']),
         'sections':len(instance['sections']),'assertion_count':instance['assertion_count'],
         'unique_boolean_ast_nodes':instance['unique_boolean_ast_nodes'],
         'boolean_only_ast_verified':True}
    if result==z3.unknown:out['reason_unknown']=solver.reason_unknown()
    if result==z3.sat:
        model=solver.model();key=[selected(model,slot) for slot in instance['keys']];witness=[]
        period=instance['period'];field=instance['field'];permit=instance['permit']
        for si,(section,chain) in enumerate(zip(instance['sections'],instance['chains'])):
            initial=selected(model,chain['initial'])
            if si==0:assert initial==0
            chosen=[group[selected(model,[v for h,skip,v in group])] for group in chain['states']]
            skips=set()
            for j,(h,skip,var) in enumerate(chosen):
                position=chain['positions'][j]
                if j:
                    previous=chain['positions'][j-1];previous_h,previous_skip,_=chosen[j-1]
                    delta=position-previous
                else:previous_h=initial;previous_skip=False;delta=position
                counts=[r for r in range(chain['limits'][j]+1)
                        if (previous_h+delta-int(previous_skip)-r)%period==h]
                assert counts;number=min(counts)
                skips.update(chain['intervals'][j][:number])
                if skip:skips.add(position)
            plain,phases,end=old.replay(section['cipher'],key,skips,initial,field)
            memberships=old.constraints(section)
            assert all(plain[p] in allowed for p,allowed in memberships.items())
            assert all(phases[p]==chosen[j][0] for j,p in enumerate(chain['positions']))
            if not permit:assert not skips
            automaton=old.exact_paths(section['cipher'],key,initial,memberships,field=field,checkpoints=False)
            assert int(automaton['compatible_path_count_decimal'])>0
            witness.append({'section':section['id'],'initial_phase':initial,'end_phase':end,
                 'skipped_F_offsets':sorted(skips),'full_output_sha256':old.digest(plain),
                 'constraint_outputs':[{'offset':p,'value':plain[p]} for p in sorted(memberships)],
                 'scalar_reencryption':True,'selected_phases_checked':True,
                 'independent_known_key_automaton_confirms_capacity':True,
                 'disabled_F_policy_has_no_skips':not skips if not permit else None})
        out['capacity_witness']={'key':key,'distinct_key_values':len(set(key)),
                                 'sections':witness,'not_a_translation':True}
    return out


def prepare():
    assert not CONTROLS.exists() and not RESULTS.exists(),'Preserve recorded outcomes.'
    old.verify();saved=old.read(old.CASES);prior=old.read(old.RESULTS)
    assert len(saved['toy_cases'])==48 and len(saved['planted_cases'])==8
    assert [q['constraint_count'] for q in saved['queries']]==[83,81]
    assert all(r['status']=='unknown' and r['reason_unknown']=='timeout' for r in prior['rows'])
    old.dump(SPEC,{'session':93,'saved_before_any_boolean_solver_check':True,
        'driver_sha256':old.sha(Path(__file__)),
        'input_hashes':{name:old.sha(ROOT/name) for name in INPUTS},
        'z3_version':z3.get_full_version(),'solver_seed':SEED,'timeout_ms':TIMEOUT,
        'query_order':[q['id'] for q in saved['queries']],
        'reused_inputs_not_regenerated':True,'only_boolean_formula_nodes':True,
        'old_integer_statuses':{r['id']:r['status'] for r in prior['rows']},
        'no_cipher_or_constraint_change':True,'no_language_score_or_plaintext_selection':True})
    print('PREPARED frozen Boolean source and exact retained inputs',flush=True)


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


def controls():
    verify();assert not CONTROLS.exists(),'Do not overwrite recorded controls.'
    inputs=old.read(old.CASES);previous=old.read(old.CONTROLS)
    statuses={(r['field'],r['period'],r['case'],r['selective_F']):r['solver']['status'] for r in previous['policy_comparisons']}
    rows=[]
    for case in inputs['toy_cases']:
      for permit in (False,True):
        field=case['field'];period=case['period'];sections=case['sections']
        expected,local=old.brute_sections(sections,period,field,permit)
        target='sat' if expected else 'unsat'
        assert target==statuses[(field,period,case['case'],permit)]
        answer=check(build(sections,period,field,permit))
        assert answer['status']==target,(case,permit,answer)
        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({'field':field,'period':period,'case':case['case'],'selective_F':permit,
            'old_integer_status':target,'brute_compatible_shared_keys':[list(k) for k in sorted(expected)],
            'status_and_key_phase_membership_agree':True,'solver':answer})
    planted=[]
    for case in inputs['planted_cases']:
        answer=check(build(case['sections'],13))
        assert answer['status']=='sat',(case['trial'],answer)
        planted.append({'trial':case['trial'],'solver':answer,
            'key_exact':answer['capacity_witness']['key']==case['planted_key'],
            'reused_capacity_control_not_recovery':True})
    old.dump(CONTROLS,{'session':93,'execution_sha256':old.sha(SPEC),'passed':True,
         'reused_toy_cases':48,'policy_comparisons':rows,'reused_planted_sets':planted,
         'no_fresh_recovery_evidence':True})
    print('CONTROLS PASS: 96 enumeration/integer parity comparisons and 8 reused planted sets',flush=True)


def screen():
    verify();control=old.read(CONTROLS)
    assert control['passed'] and control['execution_sha256']==old.sha(SPEC)
    assert not RESULTS.exists(),'Preserve recorded real outcomes; no retries.'
    prepared=[];formula_hashes={}
    for query in old.read(old.CASES)['queries']:
        instance=build(query['sections'],13)
        formula=ROOT/f"boolean_shared_{query['id']}.smt2"
        formula.write_text(instance['solver'].to_smt2())
        formula_hashes[query['id']]=old.sha(formula)
        prepared.append((query,instance,formula))
    # Both formulas and manifests are complete before either solver check.
    for query,instance,formula in prepared:
        old.dump(formula.with_suffix('.manifest.json'),{'session':93,'formula':formula.name,
            'formula_sha256':old.sha(formula),'execution_sha256':old.sha(SPEC),
            'both_formulas_saved_before_either_check':True,'paired_formula_hashes':formula_hashes,
            'only_boolean_ast_verified':True,'timeout_ms':TIMEOUT,'solver_seed':SEED})
    rows=[]
    for query,instance,formula in prepared:
        answer=check(instance)
        rows.append({'id':query['id'],'formula':formula.name,
            'formula_sha256':old.sha(formula),'manifest':formula.with_suffix('.manifest.json').name,**answer})
        old.dump(RESULTS,{'session':93,'complete':False,'rows':rows})
        print(query['id'],answer['status'],answer.get('reason_unknown',''),flush=True)
    verify()
    old.dump(RESULTS,{'session':93,'complete':True,'rows':rows,'execution_sha256':old.sha(SPEC),
        'controls_sha256':old.sha(CONTROLS),'timeout_ms':TIMEOUT,'solver_seed':SEED,
        'z3_version':z3.get_full_version(),'integer_timeouts_preserved':True,
        'no_language_score_or_plaintext_selection':True,'no_new_verified_plaintext':True})
    print('COMPLETE',[(r['id'],r['status']) for r in rows],flush=True)


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