#!/usr/bin/env python3
"""Sessions 225–226: exact historical F-clock calibration, standard library only."""
import argparse, gzip, hashlib, json, os
from collections import Counter
from itertools import product
from pathlib import Path

R = 'ᚠᚢᚦᚩᚱᚳᚷᚹᚻᚾᛁᛄᛇᛈᛉᛋᛏᛒᛖᛗᛚᛝᛟᛞᚪᚫᚣᛡᛠ'
L = 'F U TH O R K G W H N I J EO P X S T B E M L ING OE D A AE Y IO EA'.split()
POLICIES = ('never','all_printed','strict_plain','strict_coincident','optional')
DEFAULT_DIR=Path(__file__).resolve().parent

def digest(x): return hashlib.sha256(x).hexdigest()

def branches(c,k,h,t,policy):
    # h is the absolute number of consumed key positions, t=None is hidden gold.
    p = (c-k[h]) % 29
    if not ((policy=='all_printed' and c==0) or
            (policy=='strict_plain' and p==0) or
            (policy=='strict_coincident' and c==p==0)):
        if t is None or p==t: yield 'advance',h+1
    if policy!='never' and c==0 and t in (0,None):
        yield 'hold',h

def count(c,k,g,policy,details=False):
    # Number of full decision strings, not just reachable final cursor positions.
    d={0:1}; trace=[d] if details else None
    for x,t in zip(c,g):
        e=Counter()
        for h,n in d.items():
            for _,j in branches(x,k,h,t,policy): e[j]+=n
        if not e and not details: return 0
        d=dict(e)
        if details: trace.append(d)
    if not details:return sum(d.values())
    right={h:1 for h in d}; choices={}
    for i in reversed(range(len(c))):
        r={}; tally=Counter()
        for h,n in trace[i].items():
            z=sum(right.get(j,0) for _,j in branches(c[i],k,h,g[i],policy))
            if z:
                r[h]=z
                for a,j in branches(c[i],k,h,g[i],policy): tally[a]+=n*right.get(j,0)
        if c[i]==0: choices[i]={s:tally[s] for s in ['advance','hold']}
        right=r
    assert right.get(0,0)==sum(d.values())
    return {'paths':sum(d.values()),'end_cursors':d,'at_printed_F':dict(sorted(choices.items()))}

def fixtures():
    """Independent brute force: enumerate every possible printed-F mask, then render."""
    ncase=0
    for c in product(range(2),repeat=3):
      ix=[i for i,x in enumerate(c) if x==0]
      for per in product(range(2),repeat=2):
        k=list(per)*2
        for g in product((0,1,None),repeat=3):
          for pol in POLICIES:
            n=0
            for mask in range(1<<len(ix)):
                holds={i for b,i in enumerate(ix) if mask>>b&1}
                p=[];h=0
                for i,x in enumerate(c):
                    if i in holds:p.append(0)
                    else:p.append((x-k[h])%29);h+=1
                if any(t is not None and t!=v for t,v in zip(g,p)): continue
                if pol=='never' and holds:continue
                if pol=='all_printed' and holds!=set(ix):continue
                if pol=='strict_plain' and holds!={i for i,v in enumerate(p) if v==0}:continue
                if pol=='strict_coincident' and holds!={i for i in ix if p[i]==0}:continue
                n+=1
            assert count(c,k,g,pol)==n,(c,k,g,pol,n)
            ncase+=1
    assert count([0],[0],[0],'optional')==2
    return ncase

def key_prime(n):
    primes=[]
    for x in range(2,100000):
        if all(x % p for p in primes if p*p<=x): primes.append(x)
        if len(primes)==n:break
    assert len(primes)==n
    return [(p-1)%29 for p in primes]

def periodic(key,n):
    return [key[i%len(key)] for i in range(n)]

def informed_lookahead(i,h,c,k,g,held):
    # At tested printed F deliberately hide g[i], fix earlier ledger prefix then
    # take the opposite transition. Subsequent printed Fs remain optional.
    states={h+1 if held else h}
    for j in range(i+1,len(c)):
        states={nxt for st in states for _,nxt in branches(c[j],k,st,g[j],'optional')}
        if not states:return j-i
    return None

def analyze(source,pages,gs):
    gold=gs[source['name']]
    name=source['name']; ids=source['parsed_page_indices']; images=source['archive_images']
    c=[]; loc=[]
    for ix,im in zip(ids,images):
        page=[R.index(ch) for ch in pages[ix] if ch in R]
        loc+= [(im,j) for j in range(len(page))]
        c+=page
    n=len(c); assert len(gold)==n and digest(bytes(gold))==source['plaintext_rune_values_sha256']
    key=source['ordinal_key_values'];sched=periodic(key,n) if key else key_prime(n)
    hs=set(source['unenciphered_F_offsets']);h=0;rows=[]
    for i,(x,p) in enumerate(zip(c,gold)):
        held=i in hs
        if held:assert x==p==0
        else:assert p==(x-sched[h])%29
        if x==0 or p==0:
            item={'source_offset':i,'image':loc[i][0],'image_offset':loc[i][1],
                  'cipher':L[x],'gold':L[p],'ledger_next_shift':sched[h],
                  'ledger_holds':held,'ledger_cursor_before':h}
            if x==0:item['opposite_branch_dies_after_later_runes']=informed_lookahead(i,h,c,sched,gold,held)
            rows.append(item)
        h+=not held
    assert h==source['consumed_key_positions']
    policies={p:count(c,sched,gold,p) for p in POLICIES}
    hidden={}
    for label,g in [('none',gold),('printed_F',[None if x==0 else p for x,p in zip(c,gold)]),
                    ('printed_or_plain_F',[None if x==0 or p==0 else p for x,p in zip(c,gold)])]:
        hidden[label]={'hidden_positions':sum(t is None for t in g),**count(c,sched,g,'optional',True)}
    wrong={}
    if key:
        surviving=[];total=0
        for slot in range(len(key)):
            for d in range(1,29):
                alt=key.copy();alt[slot]=(alt[slot]+d)%29;total+=1
                paths=count(c,periodic(alt,n),gold,'optional')
                if paths:surviving.append([slot,d,paths])
        wrong['change_one_slot']={'tested':total,'survivors':surviving}
    survivors=[]
    for d in range(1,29):
        paths=count(c,[(x+d)%29 for x in sched],gold,'optional')
        if paths:survivors.append([d,paths])
    wrong['shift_entire_schedule']={'tested':28,'survivors':survivors}
    corrupt={p:[] for p in ('optional','strict_plain')}
    for i,x in enumerate(c):
        if x!=0:continue
        changed=gold.copy();changed[i]=(changed[i]+1)%29
        for p in corrupt:
            z=count(c,sched,changed,p)
            if z:corrupt[p].append([i,z])
    # Explicitly labelled follow-up after seeing the +1 result, not a new calibration.
    all_alts={p:[] for p in ('optional','strict_plain')}
    for i,x in enumerate(c):
        if x!=0:continue
        changed=gold.copy()
        for z in range(29):
            if z==gold[i]:continue
            changed[i]=z
            for p in all_alts:
                v=count(c,sched,changed,p)
                if v:all_alts[p].append({'offset':i,'old':L[gold[i]],'new':L[z],'paths':v})
    # Actual forward rendering of every mask still matching visible non-F gold.
    live=[(0,[],[])]
    for i,(x,t) in enumerate(zip(c,gold)):
        nxt=[]
        for h,choices,misses in live:
            for act,j in branches(x,sched,h,None if x==0 else t,'optional'):
                actual=0 if act=='hold' else (x-sched[h])%29
                nxt.append((j,choices+([i] if act=='hold' else []),
                            misses+([[i,L[t],L[actual]]] if t!=actual else [])))
        live=nxt
    assert len(live)==hidden['printed_F']['paths']
    followup={'false_gold_tested_per_policy':28*sum(x==0 for x in c),
              'successful_other_single_symbols':all_alts,
              'printed_F_gold_hidden_survivors':[{'end_cursor':j,'hold_offsets':q,
               'gold_differences_offset_old_new':m} for j,q,m in live]}
    return {'runes':n,'images':images,'source':name,'ledger_key':key or 'prime-minus-one',
            'image_lengths':dict(Counter(page for page,_ in loc)),'complete_policies':policies,
            'f_sites':rows,'optional_model_masks':hidden,'wrong_keys':wrong,
            'printed_F_gold_plus_one_successes':corrupt,'exploratory_followup':followup}

def main():
    a=argparse.ArgumentParser(description=__doc__)
    a.add_argument('--data',type=Path,default=Path(os.environ.get('CICADA_EVIDENCE_DIR',DEFAULT_DIR)))
    a.add_argument('--out',type=Path,default=DEFAULT_DIR/'f_clock_225_226_results.json.gz')
    args=a.parse_args()
    files=['liber-primus__transcription--master.txt','mechanism_coverage_results.json','increment_calibration_sources.json']
    master,ledger,src=[(args.data/f).read_text() for f in files]
    d=json.loads(ledger);g={r['name']:r['values'] for r in json.loads(src)['groups']}
    hashes={f:digest((args.data/f).read_bytes()) for f in files}
    assert hashes[files[0]]==d['master_sha256']
    pages=master[master.index('ᚱ-'):].split('%')[:73]
    results={'protocol':'f_clock_225_plan.txt','input_sha256':hashes,'exhaustive_fixture_cases':fixtures(),
             'known_sources':[analyze(s,pages,g) for s in d['known_method_groups']
                             if s['name'] in ('welcome','second_koan','lp2_56')]}
    assert len(results['known_sources'])==3
    args.out.write_bytes(gzip.compress((json.dumps(results,indent=1)+'\n').encode(),mtime=0))
if __name__=='__main__':main()
