"""Enumerate ALL strict period-nine keys and their maximum rune frequencies. python -B literal_234_nine.py output.json"""
from pathlib import Path
import sys,json,subprocess,tempfile
from collections import Counter
import numpy as np
from line_mechanism_108 import geometry
from lp_core import LET
def bounds(x,k):
    # Independently drive the complete key, once for each target; rows are phases, columns are distinct fixed target objectives.
    st=np.full((len(k),29),-10000,dtype=np.int32);st[0,:]=0
    kk=np.array(k);R=np.arange(29);opt=np.full(len(k),10000,dtype=int);opt[0]=0
    active={0}
    for c in x:
        h0={h for h in active if c!=k[h]};active=({(h+1)%len(k) for h in h0}|(active if c==0 else set()))
        if not active:return None
        plain=(c-kk)%29
        norm=st+(plain[:,None]==R);norm[plain==0,:]=-10000
        advance=np.roll(norm,1,axis=0)
        lo=np.roll(np.where(plain!=0,opt+(kk!=0),10000),1)
        if c==0:advance=np.maximum(advance,st+(R==0));lo=np.minimum(lo,opt)
        st=advance;opt=lo
    return dict(count_caps=st.max(0).tolist(),minimum_positions_changed=int(opt.min()))
def run():
    g,_=geometry();x=[z[3] for z in g if z[1]==8]
    with tempfile.TemporaryDirectory() as t:
        b=Path(t)/'nine';subprocess.run(['c++','-O3','-std=c++17',str(Path(__file__).with_suffix('.cpp')),'-o',str(b)],check=True)
        lines=subprocess.check_output([str(b)],input=' '.join(map(str,x)),text=True).splitlines()
    calls,pruned,n=map(int,lines[0].split());classes=[list(map(int,l.split())) for l in lines[1:]];assert len(classes)==n
    good=[]
    for k in classes:
        ok=0
        for v in sorted({tuple(k[i:]+k[:i]) for i in range(9)}):
            scores=bounds(x,v)
            if scores is not None:good.append(dict(key=v,**scores));ok+=1
        assert ok
    rmax=np.array([z['count_caps'] for z in good]).max(0)
    return dict(calls=calls,pruned=pruned,nonzero_rotation_classes=classes,valid_ordered_nonzero=good,alphabet=LET,conditional_single_rune_caps=rmax.tolist(),max_concentration=int(rmax.max()),positions_changed_min=min(z['minimum_positions_changed'] for z in good),caps_exclude_identity=True)
if __name__=='__main__':
    r=run();Path(sys.argv[1]).write_text(json.dumps(r,separators=(',',':'))+'\n');print(len(r['nonzero_rotation_classes']),len(r['valid_ordered_nonzero']),r['max_concentration'],r['positions_changed_min'])
