"""Rebuild S229–230 in the evidence directory:
python -B fcaps_230_verify.py fcaps_229_230_results.json
With a split working tree, supply --evidence DIR --other SOLVER_RESULTS.json.
Requires a C++17 compiler; all executables and intermediate inputs are temporary.
"""
import argparse, gzip, hashlib, itertools, json, subprocess, tempfile
from pathlib import Path
from fcaps_229_source import load
LABELS=['free_rotations_decoupled_F','blocks_1','blocks_2','blocks_4','blocks_8','blocks_16','blocks_32','blocks_64','exact','never','always']
TYPES=['ordinary','F']

def cpp(exe,x,q):
    inp=' '.join(map(str,[q,len(x),*x]))
    s=subprocess.check_output([str(exe)],input=inp,text=True).splitlines()
    n,nf,nr,coarse,keys=map(int,s[0].split());assert n==len(x)
    out=dict(n=n,printed_F=nf,strips=nr,stripwise_non_F=coarse,representatives=keys,ordinary={},F={})
    for line in s[1:]:
        t,j,v,*z=map(int,line.split());out[TYPES[t]][LABELS[j]]=dict(value=v,z=z)
    return out

def literal(x,z,t,holds,ph=0):
    hs=set(holds);count=0;literal_F=0;advanced_F=0;other=0
    assert all(0<=i<len(x) and x[i]==0 for i in hs)
    for i,v in enumerate(x):
        if i in hs:
            count+=int(t);literal_F+=int(t)
        else:
            if v==z[ph]:
                count+=1
                if v==0:advanced_F+=1
                else:other+=1
            ph=(ph+1)%4
    assert count==literal_F+advanced_F+other
    return dict(count=count,held_F_hits=literal_F,advanced_F_hits=advanced_F,non_F_printed_hits=other,holds=len(hs),ending_phase=ph)

def paths(x,z,t,phase=None):
    # Direct glyph-by-glyph recurrence; no strip aggregation or independent starts at any inner positions.
    v=[0 if phase is None or i==phase else -10**8 for i in range(4)];trace=[]
    for c in x:
        out=[0]*4;pred=[]
        for p in range(4):
            prev=(p-1)%4;adv=v[prev]+int(c==z[prev]);hold=v[p]+int(t) if c==0 else -10**8-1
            out[p]=max(adv,hold);pred.append(hold>adv)
        trace.append(pred);v=out
    p=max(range(4),key=v.__getitem__);score=v[p];hs=[]
    for i in reversed(range(len(x))):
        if trace[i][p]:hs.append(i)
        else:p=(p-1)%4
    hs.reverse();r=literal(x,z,t,hs,p);assert r['count']==score and (phase is None or p==phase)
    return dict(starting_phase=p,held=hs,**r)

def exhaustive(x,q):
    idx=[i for i,v in enumerate(x) if v==0];possible=[[idx[i] for i in range(len(idx)) if m>>i&1] for m in range(1<<len(idx))]
    out=[dict(exact=0,never=0,always=0) for t in TYPES]
    for z in itertools.product(range(q),repeat=4):
        for hs in possible:
            p=0;v=0
            for i,c in enumerate(x):
                if i not in hs:v+=int(c==z[p]);p=(p+1)%4
            for t in range(2):
                s=v+t*len(hs);o=out[t];o['exact']=max(s,o['exact'])
                if not hs:o['never']=max(s,o['never'])
                if len(idx)==len(hs):o['always']=max(s,o['always'])
    return out

def loose(x,z,t):
    strips=[[]]
    for c in x:
        if c: strips[-1].append(c)
        else:strips.append([])
    phases=[];hits=[]
    for s in strips:
        four=[sum(c==z[(i+j)%4] for i,c in enumerate(s)) for j in range(4)]
        j=four.index(max(four));phases.append(j);hits.append(four[j])
    non=sum(hits);ff=x.count(0) if t or 0 in z else 0
    return dict(non_F_printed_hits=non,optimistic_printed_F=ff,total=non+ff,starting_phases=phases)

def run(evd,other,script):
    x=load(evd);q=29
    with tempfile.TemporaryDirectory(prefix='cicada_fcap_') as td:
        exe=Path(td)/'check';subprocess.run(['c++','-O3','-std=c++17',str(script/'fcaps_229_relax.cpp'),'-o',str(exe)],check=True)
        out=cpp(exe,x,q);out['rune_byte_sha256']=hashlib.sha256(bytes(x)).hexdigest();out['independent_tiny_cases']=0
        for seq in itertools.product(range(3),repeat=4):
            exp=exhaustive(seq,3);res=cpp(exe,seq,3)
            for t,name in enumerate(TYPES):
                assert all(exp[t][m]==res[name][m]['value'] for m in ['exact','always','never'])
                assert min(res[name][k]['value'] for k in LABELS[:8])>=exp[t]['exact']
            out['independent_tiny_cases']+=1
        # These length-3316 fixtures have a known attainable maximum of n, whatever solver is used.
        z_E=[0,5,14,20];sy=[z_E[i%4] for i in range(len(x))];r=literal(sy,z_E,False,[]);assert r['count']==len(x)
        # Check the exact solver for both planted clocks, as well as direct re-encryption.
        a=cpp(exe,sy,q);assert a['ordinary']['exact']['value']==len(x)
        z_F=[4,11,2,15];ph=0;sy=[];hs=[]
        for i,c in enumerate(x):
            if c==0:sy.append(0);hs.append(i)
            else:sy.append(z_F[ph]);ph=(ph+1)%4
        f=literal(sy,z_F,True,hs);assert f['count']==len(x)
        b=cpp(exe,sy,q);assert b['F']['exact']['value']==len(x)
        out['planted']={'E_advance_all':r,'F_hold_at_actual_131':f}
    for t,name in enumerate(TYPES):
        full=out[name];raw=full['free_rotations_decoupled_F'];u=loose(x,raw['z'],t);assert u['total']==raw['value'];raw['witness']=u
        e=full['exact'];v=paths(x,e['z'],t);assert v['count']==e['value']
        normalized=e['z'][v['starting_phase']:]+e['z'][:v['starting_phase']]
        assert literal(x,normalized,t,v['held'])['count']==e['value']
        e['direct_witness']=v;e['phase_0_z']=normalized
        for label,hold in [('never',[]),('always',[i for i,c in enumerate(x) if not c])]:
            v=full[label]
            sr=[literal(x,v['z'],t,hold,p) for p in range(4)]
            ix=max(range(4),key=lambda p:sr[p]['count']);assert v['value']==sr[ix]['count'];v['start']=ix
        vals=[full[k]['value'] for k in LABELS[:9]];assert all(b<=a for a,b in zip(vals,vals[1:]))
    if other:
        raw=json.loads(gzip.decompress(other.read_bytes()) if other.suffix=='.gz' else other.read_bytes());out['other_solver_sha256']=hashlib.sha256(other.read_bytes()).hexdigest()
        out['other_witness_replay']=other_replay(raw,x,out)
    return out

def other_replay(raw,x,out):
    result={}
    for name,t,target in [('E',0,18),('F',1,0)]:
        vals=[]
        for w in raw['targets'][name]['winners']:
            z=[(target+k)%29 for k in w['key']]
            assert len(w['holds'])==len(set(w['holds']))
            rep=literal(x,z,t,w['holds'],0)
            assert rep['count']==w['score']==out[TYPES[t]]['exact']['value']
            assert rep['count']==paths(x,z,t,phase=0)['count']
            vals.append(dict(key=w['key'],normalized=z,**rep))
        assert len(vals)==[2,1][t]
        result[name]=vals
    return result

if __name__=='__main__':
    p=argparse.ArgumentParser();p.add_argument('output',type=Path);here=Path(__file__).resolve().parent
    p.add_argument('--evidence',type=Path,default=here);p.add_argument('--other',type=Path)
    a=p.parse_args();other=a.other or a.evidence/'holds_227_228_results.json.gz';result=run(a.evidence.resolve(),other,here);a.output.write_text(json.dumps(result,indent=2,sort_keys=True)+'\n')
