"""Cross-verify the compiled upper bounds on every original Second Koan cell.
Independent oracle: Session 115 direct table construction and exact cyclic fits.
"""
import math,subprocess,tempfile
from pathlib import Path
import numpy as np
from welcome_116 import D,train,bounds,factors,fs_at,maskslots,top2,read
def main():
    tabs,_,ci,_=train();b,c=next((b,v) for n,pg,b,v in ci if n=='second_koan' and pg==(0,0))
    fs=np.flatnonzero(c==0);prior=read('hidden_f_115_results.json')['rows']['original'];checked=0
    with tempfile.TemporaryDirectory() as tmp:
        exe=Path(tmp)/'bound';subprocess.run(['g++','-O3','-std=c++17','-fopenmp','-march=native','-ffp-contract=off',str(D/'welcome_bounds_116.cpp'),'-o',str(exe)],check=True)
        for name,t in tabs.items():
            tab=bounds(exe,c,b,t);rows=[]
            for row in range(14):
                L=row+3;pen=L*math.log2(29)
                for m,u in enumerate(tab[row]):
                    sk=fs_at(fs,m);E=factors(c,maskslots(len(c),L,sk),b,t,L);dp=np.zeros(29)
                    for a in E:dp=(a+dp[:,None]).max(axis=0)
                    assert abs(u-(dp.max()-pen))<1e-7
                    for key,v in top2(E):
                        assert u>=v-pen-1e-7;rows.append((v-pen,key,sk))
                    checked+=1
            rows.sort(key=lambda x:-x[0])
            for (v,k,s),ref in zip(rows[:2],(prior[name]['winner'],prior[name]['rival'])):
                assert abs(v-ref['penalized'])<1e-7 and k==ref['key'] and s==ref['skips']
    print(checked,'bounds verified; both exact winners and runners reproduced.')
if __name__=='__main__':main()
