"""S270/S271. python -B split_270.py NOTEBOOK_FILES BLIND.json PREDICTIONS.json
Only library imports training from the historical solved sources. No test labels or method metadata accepted.
"""
from pathlib import Path
from collections import Counter
import hashlib,json,sys,random,importlib.util
SRC=Path(sys.argv[1]).resolve() if len(sys.argv)>1 else Path(__file__).resolve().parent
def historical():
    mpath=SRC/'transfer_261_262.py';sy=sys.argv
    sp=importlib.util.spec_from_file_location('published_261',mpath);mod=importlib.util.module_from_spec(sp)
    try:
        sys.argv=['published_261.py','-',str(SRC)];sp.loader.exec_module(mod)
    finally:sys.argv=sy
    return mod
H=historical()
# Partial state: maximum score; fewest supporting hit positions at that score; strongest eligible
# (length,-position) among any such path; unique equal-score partial phrase, or None if ambiguous.
EMPTY=(0,0,(0,0),())
def merge(a,b):
    if a is None or b[0]>a[0]:return b
    if b[0]<a[0]:return a
    return a[0],min(a[1],b[1]),max(a[2],b[2]),a[3] if a[3]==b[3] else None
def eligible(i,gap,side):
    return (side in ('L','P') and i<gap-2) or (side in ('R','P') and i>=gap+2)
def dp(ww,gap,rule,lex,side,skip):
    f,restart=rule;st={0:EMPTY}
    for i,c in enumerate(ww):
        if not st:return None
        if i==gap and restart:
            one=None
            for v in st.values():one=merge(one,v)
            st={0:one}
        m=gap-2<=i<gap+2;can=eligible(i,gap,side) and i!=skip and len(c)>=3;nxt={}
        for clk,(score,hits,anchor,p) in st.items():
            for k,w in H.outword(c,f,clk):
                z=len(w) if can and w in lex else 0
                val=(score+z,hits+bool(z),max(anchor,(z,-i)) if z else anchor,
                     p+(w,) if m and p is not None else p)
                nxt[k]=merge(nxt.get(k),val)
        st=nxt
    ans=None
    for candidate in st.values():ans=merge(ans,candidate)
    return ans
def panel(ww,gap,lex,side,skip=None,minhits=2,minscore=6):
    fams={H.tag(*rule):dp(ww,gap,rule,lex,side,skip) for rule in H.RULES};top=None
    for x in fams.values():
        if x is not None:top=merge(top,x)
    if top is None:return dict(call=None,reason='no_legal_rule',top_score=None,min_hits=0,top_rules=[],strongest_position=None)
    score,hits,anchor,p=top;assert p is None or len(p)==4
    reason='called' if p is not None and hits>=minhits and score>=minscore else 'no_lexical_evidence' if score==0 else 'low_evidence' if hits<minhits or score<minscore else 'phrase_tie'
    return dict(call=p if reason=='called' else None,reason=reason,top_score=score,min_hits=hits,
                phrase_unique=p is not None,top_rules=[k for k,v in fams.items() if v is not None and v[0]==score],
                strongest_position=(-anchor[1]) if anchor[0] else None,strongest_length=anchor[0])
def do(ww,gap,lex):
    assert 2<=gap<=len(ww)-2 and all(len(w)>0 for w in ww) and all(0<=r<29 for w in ww for r in w)
    L,R,P=[panel(ww,gap,lex,t) for t in ('L','R','P')]
    call=L['call'] if L['call'] is not None and L['call']==R['call'] else None
    reason='agree' if call is not None else 'different_phrases' if L['call'] is not None and R['call'] is not None else 'one_side_only' if L['call'] is not None or R['call'] is not None else 'neither_side'
    reduced=[]
    for d,t in [(L,'L'),(R,'R')]:
        pos=d['strongest_position']; reduced.append(panel(ww,gap,lex,t,pos,1,3) if pos is not None else None)
    kept=call is not None and all(q is not None and q['call']==call for q in reduced)
    return dict(guess=call,decision=reason,left=L,right=R,pooled=P,left_without_top=reduced[0],right_without_top=reduced[1],stable=kept)
def small_brute(ww,gap,rule,lex,t,skip):
    f,r=rule;st=[(0,(),[],())] # clk, words, outside hit pairs, phase-free dummy
    for i,c in enumerate(ww):
        nxt=[]
        for clk,phrase,hits,_ in st:
            for k,w in H.outword(c,f,0 if r and i==gap else clk):
                h=hits+([(len(w),-i)] if eligible(i,gap,t) and i!=skip and w in lex else [])
                nxt.append((k,phrase+(w,) if gap-2<=i<gap+2 else phrase,h,()))
        st=nxt
    if not st:return None
    high=max(sum(x for x,_ in h) for k,w,h,_ in st)
    keep=[(w,h) for k,w,h,_ in st if sum(x for x,_ in h)==high]
    phrases={q for q,_ in keep};besthit=max([q for w,h in keep for q in h]+[(0,0)])
    return high,min(len(h) for _,h in keep),besthit,next(iter(phrases)) if len(phrases)==1 else None
def fixture():
    rng=random.Random(270);total=0;acc=Counter()
    for n in range(22):
        ww=[tuple(rng.randrange(10) if rng.random()>.20 else 0 for _ in range(rng.choice((1,2,3,4)))) for _ in range(8)];gap=4
        lex={p for w in ww if len(w)>=3 for f,_ in H.RULES for clk in range(4) for k,p in H.outword(w,f,clk) if rng.random()>.45}
        for rule in H.RULES:
            for t in ['L','R','P']:
                skip=rng.choice((None,0,7))
                a=small_brute(ww,gap,rule,lex,t,skip);b=dp(ww,gap,rule,lex,t,skip)
                assert a==b,(ww,rule,a,b)
                acc['dead' if a is None else 'tied' if a[3] is None else 'unique']+=1;total+=1
    return {'scalars_checked':total,'outcomes':acc}
def main():
    if len(sys.argv)==3 and sys.argv[2]=='--check':
        print(fixture());return
    dest=Path(sys.argv[3]);bl=Path(sys.argv[2]);data=json.loads(bl.read_text())
    cases=data if isinstance(data,list) else data['cases'];src=H.sources();lex,_=H.tables(src)
    tested=fixture();outputs=[]
    for case in cases:
        # No metadata (not even fold or id) passed into do(); attach opaque ID only afterwards.
        ww=[tuple(w) for w in case['words']]; o=do(ww,int(case['gap']),lex);o['id']=case['id'];outputs.append(o)
    assert len({o['id'] for o in outputs})==len(cases)
    record=dict(protocol_sha256=hashlib.sha256(Path(__file__).resolve().with_name('split_270_plan.txt').read_bytes()).hexdigest(),
                blind_sha256=hashlib.sha256(bl.read_bytes()).hexdigest(),case_count=len(cases),historical_vocabulary_size=len(lex),
                fixture=tested,predictions=outputs)
    dest.write_text(json.dumps(record,sort_keys=True,separators=(',',':'))+'\n')
    print(len(outputs),Counter(x['decision'] for x in outputs),sum(o['stable'] for o in outputs),hashlib.sha256(dest.read_bytes()).hexdigest())
if __name__=='__main__':main()
