"""Session 92: exact shared-array singleton capacity, not decryption.

Python, NumPy, z3-solver. Run prepare, controls, then screen. All historical
sources remain read only; real queries use the fixed 30-second solver limit.
"""
from pathlib import Path
import argparse
import hashlib
import itertools
import json
import random
import time

import z3
from lp_core import ROOT, lp, vals
from lexical_words import tokenize_words
from solved_mechanism_audit import exact_paths

PLAN=ROOT/'shared_periodic_capacity_next_plan.json'
CASES=ROOT/'shared_periodic_cases.json'
SPEC=ROOT/'shared_periodic_execution.json'
CONTROLS=ROOT/'shared_periodic_controls.json'
RESULTS=ROOT/'shared_periodic_results.json'
SEED=330192
TIMEOUT=30000
EXEMPT={(6,75),(54,0)}
INPUTS=['shared_periodic_capacity_next_plan.json','lp_core.py','word_core.py',
        'lexical_words.py','solved_mechanism_audit.py','unknown_periodic_audit.py',
        'unknown_periodic_results.json','liber-primus__transcription--master.txt']


def read(path):return json.loads(path.read_text())
def sha(path):return hashlib.sha256(path.read_bytes()).hexdigest()
def digest(values):return hashlib.sha256(bytes(values)).hexdigest()
def dump(path,value):path.write_text(json.dumps(value,indent=2,ensure_ascii=False)+'\n')
def constraints(section):return {int(i):set(v) for i,v in section['constraints'].items()}


def replay(cipher,key,skips,initial,field):
    phase=initial;plain=[];phases=[];encoded=[]
    for i,c in enumerate(cipher):
        phases.append(phase)
        if i in skips:
            assert c==0;p=0;inverse=0
        else:
            p=(c-key[phase])%field;inverse=(p+key[phase])%field
            phase=(phase+1)%len(key)
        plain.append(p);encoded.append(inverse)
    assert encoded==cipher
    return plain,phases,phase


def solve(sections,period,field=29,permit=True,formula=None):
    solver=z3.Solver();solver.set(timeout=TIMEOUT,random_seed=SEED)
    key=[z3.Int(f'key_{j}') for j in range(period)]
    for k in key:solver.add(k>=0,k<field)
    chains=[]
    for si,section in enumerate(sections):
        cipher=section['cipher'];memberships=constraints(section);positions=sorted(memberships)
        initial=z3.Int(f's{si}_initial_phase');solver.add(initial>=0,initial<period)
        if si==0:solver.add(initial==0)
        phases=[];counts=[];actions=[];intervals=[]
        for j,position in enumerate(positions):
            allowed=memberships[position]
            phase=z3.Int(f's{si}_phase_{j}');solver.add(phase>=0,phase<period)
            previous=positions[j-1] if j else -1
            available=[i for i in range(previous+1,position) if cipher[i]==0]
            count=z3.Int(f's{si}_interval_skips_{j}')
            solver.add(count>=0,count<=min(len(available),period-1) if permit else count==0)
            if j:
                solver.add(phase==(phases[-1]+position-previous-count-z3.If(actions[-1],1,0))%period)
            else:solver.add(phase==(initial+position-count)%period)
            can_skip=permit and cipher[position]==0 and 0 in allowed
            skip=z3.Bool(f's{si}_skip_constraint_{j}') if can_skip else z3.BoolVal(False)
            normal=z3.Or(*[z3.And(phase==h,z3.Or(*[key[h]==(cipher[position]-p)%field for p in sorted(allowed)])) for h in range(period)])
            solver.add(z3.Or(skip,z3.And(z3.Not(skip),normal)))
            phases.append(phase);counts.append(count);actions.append(skip);intervals.append(available)
        chains.append((initial,positions,phases,counts,actions,intervals))
    if formula:
        formula.write_text(solver.to_smt2())
        # The formula and its provenance exist before solver.check().
        dump(formula.with_suffix('.manifest.json'),{'session':92,'formula':formula.name,
             'formula_sha256':sha(formula),'execution_sha256':sha(SPEC),
             'saved_before_check':True,'timeout_ms':TIMEOUT,'seed':SEED})
    start=time.monotonic();result=solver.check();elapsed=time.monotonic()-start
    out={'status':str(result),'solver_seconds':round(elapsed,6),
         'constraints':sum(len(constraints(s)) for s in sections),'sections':len(sections)}
    if formula:out.update(formula=formula.name,formula_sha256=sha(formula),manifest=formula.with_suffix('.manifest.json').name)
    if result==z3.unknown:out['reason_unknown']=solver.reason_unknown()
    if result==z3.sat:
        model=solver.model();array=[model.eval(k,model_completion=True).as_long() for k in key];witness=[]
        for si,(section,chain) in enumerate(zip(sections,chains)):
            initial,positions,phases,counts,actions,intervals=chain
            phase0=model.eval(initial,model_completion=True).as_long();skips=set()
            for j,available in enumerate(intervals):
                number=model.eval(counts[j],model_completion=True).as_long();skips.update(available[:number])
                if z3.is_true(model.eval(actions[j],model_completion=True)):skips.add(positions[j])
            plain,actual,end=replay(section['cipher'],array,skips,phase0,field)
            allowed=constraints(section)
            assert all(plain[i] in values for i,values in allowed.items())
            assert all(actual[p]==model.eval(phases[j]).as_long() for j,p in enumerate(positions))
            if not permit:assert not skips
            if permit:
                independent=exact_paths(section['cipher'],array,phase0,allowed,field=field,checkpoints=False)
                assert int(independent['compatible_path_count_decimal'])>0
            witness.append({'section':section['id'],'initial_phase':phase0,'end_phase':end,
                 'skipped_F_offsets':sorted(skips),'full_output_sha256':digest(plain),
                 'constraint_outputs':[{'offset':i,'value':plain[i]} for i in sorted(allowed)],
                 'scalar_reencryption':True,'phase_memberships_checked':True,
                 'independent_known_key_automaton_confirms_capacity':bool(permit)})
        out['capacity_witness']={'key':array,'sections':witness,'not_a_translation':True}
    return out


def brute_sections(sections,period,field,permit):
    compatible={};local=[set() for _ in sections]
    for key in itertools.product(range(field),repeat=period):
        options=[]
        for si,section in enumerate(sections):
            fs=[i for i,c in enumerate(section['cipher']) if c==0]
            masks=list(itertools.product([False,True],repeat=len(fs))) if permit else [tuple(False for _ in fs)]
            phases=[]
            for initial in (range(period) if si else [0]):
                for mask in masks:
                    skipped={i for i,yes in zip(fs,mask) if yes}
                    plain,_,_=replay(section['cipher'],list(key),skipped,initial,field)
                    if all(plain[i] in allowed for i,allowed in constraints(section).items()):
                        phases.append(initial);break
            if phases:local[si].add(key)
            options.append(phases)
        if all(options):compatible[key]=options
    return compatible,local


def toy_cases():
    rng=random.Random(SEED);out=[]
    for field in (3,5):
      for period in (1,2,3):
       for case in range(8):
        sections=[]
        for si in range(2):
            cipher=[rng.randrange(field) for _ in range(6)]
            for i in [i for i,c in enumerate(cipher) if c==0][3:]:cipher[i]=1
            memberships={i:[rng.randrange(field)] for i in [0,3,5]}
            if case==1:
                key=list(range(period));phase=0 if si==0 or period==1 else 1
                cipher=[(1+key[(i+phase)%period])%field for i in range(6)]
                memberships={i:[1] for i in range(6)}
            elif case==2:
                cipher=[1]*6;memberships={i:[1 if si==0 else 2] for i in range(6)}
            elif case==3 and si==0:memberships[3]=[]
            elif case==4:
                cipher=[rng.randrange(1,field) for _ in range(6)]
                for i in [0,3,5]:cipher[i]=0
                memberships={i:[0] for i in [0,3,5]}
            elif case==5:
                cipher=[rng.randrange(1,field),0,0,0,rng.randrange(1,field),rng.randrange(1,field)]
                memberships[3]=[1]
            elif case==6:
                cipher=[rng.randrange(1,field) for _ in range(6)];memberships[0]=list(range(field))
            elif case==7:
                cipher=[0]+[rng.randrange(1,field) for _ in range(4)]+[0]
                memberships={i:[rng.randrange(field)] for i in [1,4]}
            assert cipher.count(0)<=3
            sections.append({'id':si,'cipher':cipher,'constraints':memberships})
        out.append({'field':field,'period':period,'case':case,'sections':sections})
    return out


def planted_cases():
    out=[]
    for trial in range(8):
        rng=random.Random(SEED+trial);key=[rng.randrange(29) for _ in range(13)];sections=[];gold=[]
        for si in range(3):
            plain=[rng.randrange(29) for _ in range(80)]
            for i in [0,17,40,79]:plain[i]=rng.choice([24,10,3])
            for i in [8,31,62]:plain[i]=0
            initial=0 if si==0 else rng.randrange(13);phase=initial;ordinal=0;cipher=[];skips=[]
            for i,p in enumerate(plain):
                skip=p==0 and ordinal%2==trial%2
                if p==0:ordinal+=1
                if skip:cipher.append(0);skips.append(i)
                else:cipher.append((p+key[phase])%29);phase=(phase+1)%13
            assert replay(cipher,key,set(skips),initial,29)[0]==plain
            sections.append({'id':si,'cipher':cipher,'constraints':{i:[24,10,3] for i in [0,17,40,79]}})
            gold.append({'plain':plain,'initial_phase':initial,'skipped_F_offsets':skips})
        out.append({'trial':trial,'seed':SEED+trial,'planted_key':key,'sections':sections,'construction_gold':gold})
    return out


def prepare():
    assert not RESULTS.exists() and not CONTROLS.exists(),'Preserve recorded outcomes.'
    master=ROOT/'liber-primus__transcription--master.txt'
    assert sha(master)=='b0b2e13c3cd35512ee5955a2d9a56c22d7410e283d35dd9c90abbaa7b99279eb'
    source='%'.join(lp[:56]);words=tokenize_words(source);singletons=[w for w in words if len(w['values'])==1]
    assert len(singletons)==83
    sections=[];start=0
    for number,piece in enumerate(source.split('$')):
        cipher=vals(piece).tolist()
        if len(cipher)>100:
            memberships=[{'local_offset':w['rune_offset']-start,'page':w['page'],
                'page_rune_offset':w['page_rune_offset'],'global_offset':w['rune_offset'],
                'cipher_value':w['values'][0],'prior_red_exemption':(w['page'],w['page_rune_offset']) in EXEMPT}
                for w in singletons if w['section']==number]
            assert all(cipher[w['local_offset']]==w['cipher_value'] for w in memberships)
            sections.append({'id':number,'cipher':cipher,'global_start':start,'singletons':memberships})
        start+=len(cipher)
    assert [s['id'] for s in sections]==[0,1,2,4,5,6,7,8]
    assert sum(len(s['cipher']) for s in sections)==12947
    assert sum(len(s['singletons']) for s in sections)==83
    assert sum(w['prior_red_exemption'] for s in sections for w in s['singletons'])==2
    queries=[]
    for exempt in (False,True):
        selected=[{'id':s['id'],'cipher':s['cipher'],
             'constraints':{w['local_offset']:[3,10,24] for w in s['singletons'] if not(exempt and w['prior_red_exemption'])}}
             for s in sections]
        count=sum(len(s['constraints']) for s in selected);assert count==(81 if exempt else 83)
        queries.append({'id':'AIO_prior_red_exemptions' if exempt else 'AIO_all_singletons',
                        'constraint_count':count,'sections':selected})
    dump(CASES,{'session':92,'real_section_layout':sections,'queries':queries,
                'toy_cases':toy_cases(),'planted_cases':planted_cases()})
    dump(SPEC,{'session':92,'saved_before_controls_and_real_queries':True,
          'driver_sha256':sha(Path(__file__)),'cases_sha256':sha(CASES),
          'input_hashes':{name:sha(ROOT/name) for name in INPUTS},
          'z3_version':z3.get_full_version(),'timeout_ms':TIMEOUT,'solver_seed':SEED,
          'first_initial_phase':0,'other_initial_phases':'Free integers 0..period-1',
          'toy_construction':'Persistent random.Random(330192), field/period/case/section order. Cases 1 and 2 force phase/zero-slot and shared-vs-local checks; remaining patterns exercise empty, F-only, adjacent-F, absent-F and edge-F constraints.',
          'query_order':[q['id'] for q in queries],
          'no_language_score_or_plaintext_selection':True})
    print('PREPARED 48 toy cases, 8 planted sets, 2 real query inputs',flush=True)


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


def controls():
    verify();assert not CONTROLS.exists(),'Do not overwrite control outcomes.'
    saved=read(CASES);toys=[]
    for case in saved['toy_cases']:
      for permit in (False,True):
        sections=case['sections'];period=case['period'];field=case['field']
        expected,local=brute_sections(sections,period,field,permit)
        got=solve(sections,period,field,permit)
        assert got['status']==('sat' if expected else 'unsat'),(case,permit,got)
        if expected:
            witness=got['capacity_witness'];key=tuple(witness['key'])
            assert key in expected
            assert all(s['initial_phase'] in expected[key][i] for i,s in enumerate(witness['sections']))
        if case['case']==2:assert not expected and all(local)
        if case['case']==1 and period>1:
            assert expected and all(options[1]==[1] for options in expected.values())
        toys.append({'field':field,'period':period,'case':case['case'],'selective_F':permit,
                     'brute_compatible_shared_keys':len(expected),
                     'brute_local_compatible_keys':[len(k) for k in local],
                     'shared_local_contradiction_fixture':case['case']==2,
                     'nonzero_second_phase_required':case['case']==1 and period>1,
                     'exact_status_agreement':True,'solver':got})
    planted=[]
    for case in saved['planted_cases']:
        for section,gold in zip(case['sections'],case['construction_gold']):
            plain,_,_=replay(section['cipher'],case['planted_key'],set(gold['skipped_F_offsets']),gold['initial_phase'],29)
            assert plain==gold['plain'] and all(plain[i] in allowed for i,allowed in constraints(section).items())
        got=solve(case['sections'],13)
        assert got['status']=='sat',(case['trial'],got)
        planted.append({'trial':case['trial'],'seed':case['seed'],'solver':got,
             'planted_construction_roundtrip':True,'key_exact':got['capacity_witness']['key']==case['planted_key'],
             'capacity_not_recovery':True})
    dump(CONTROLS,{'session':92,'execution_sha256':sha(SPEC),'passed':True,
         'toy_cases':48,'policy_comparisons':toys,'planted_shared_sets':planted,
         'no_language_or_recovery_claim':True})
    print('CONTROLS PASS',len(toys),'exhaustive policy comparisons;',len(planted),'planted shared sets',flush=True)


def screen():
    verify();control=read(CONTROLS)
    assert control['passed'] and control['execution_sha256']==sha(SPEC)
    assert not RESULTS.exists(),'Preserve recorded outcomes; no retries.'
    rows=[]
    for query in read(CASES)['queries']:
        formula=ROOT/f"shared_periodic_{query['id']}.smt2"
        got=solve(query['sections'],13,formula=formula)
        rows.append({'id':query['id'],**got})
        dump(RESULTS,{'session':92,'complete':False,'rows':rows})
        print(query['id'],got['status'],got.get('reason_unknown',''),flush=True)
    verify()
    dump(RESULTS,{'session':92,'complete':True,'rows':rows,'execution_sha256':sha(SPEC),
         'controls_sha256':sha(CONTROLS),'timeout_ms':TIMEOUT,'solver_seed':SEED,
         'z3_version':z3.get_full_version(),'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]()
