"""Mechanical derivation of fresh tool fixtures; zero DB/HTTP."""
from pathlib import Path
import json, re, shutil
HERE=Path(__file__).resolve().parent
RUN=Path('/tmp/cdx-ai-core-direct002-20261011')
prior=json.loads((HERE/'exact-prior-SQL-bind-exemplars.json').read_text())
def amount(v):
    if isinstance(v,float): return {0.01:0.02,-0.01:-0.02,0.99:0.97}.get(v,v)
    if isinstance(v,str): return {'0.01':'0.02','-0.01':'-0.02','0.99':'0.97','CDXCORE11S1_DIRECT':'CDXCORE11S1_DIRECT_002'}.get(v,v)
    return v
for lane in ['B','C']:
    entries=prior[lane]
    for e in entries:
        e['queryString']=e['queryString'].replace('+ 0.01','+ 0.02')
        for pair in e['bind_plan'].values(): pair[0]=amount(pair[0])
    fixture={'lane':lane,'ids':json.loads((RUN/f'seed-{lane}/prepared.json').read_text())['ids'],'entries':entries}
    (RUN/f'seed-{lane}/exact-SQL-bind-plan.json').write_text(json.dumps(fixture,ensure_ascii=False,indent=2)+'\n')
(HERE/'exact-new-SQL-bind-plan.json').write_text(json.dumps(prior,ensure_ascii=False,indent=2)+'\n')
native=(HERE/'tools/NativePdo.php').read_text()
needle="if(in_array($kind,['INSERT','UPDATE'],true))self::bindTypes($db,$sql,$bind);"
assert needle in native
native=native.replace(needle,"if(in_array($kind,['INSERT','UPDATE'],true)){global $runtime;$shape=static function($s){$s=preg_replace('/[`\\\"]([a-zA-Z_][a-zA-Z0-9_]*)[`\\\"]/','$1',$s);$s=preg_replace('/:\\w+/',':B',$s);return trim(preg_replace('/\\s+/',' ',$s));};$plans=json_decode(file_get_contents($runtime.'/exact-SQL-bind-plan.json'),true)['entries'];$matches=array_values(array_filter($plans,static function($p)use($db,$sql,$shape){return $p['connection']===$db&&$shape($p['queryString'])===$shape($sql);}));ck(count($matches)===1,'Exact original DML SQL shape/field order/predicates');self::bindTypes($db,$sql,$bind);}")
(HERE/'tools/NativePdo.php').write_text(native)
for src in (HERE/'tools').iterdir():
    if src.is_file():shutil.copyfile(src,RUN/src.name)
print(json.dumps({'new_exact_SQL_plans':12,'SQL':0,'HTTP':0}))
