from pathlib import Path
import json,hashlib,shutil,tarfile,io
HERE=Path(__file__).resolve().parent;P=HERE.parent;PRIOR=Path('/tmp/cdx-ai-customer-weight-retest-20261011');RUN=Path('/tmp/cdx-ai-final-weight-read-20261011');MAIN=Path('/Users/wiscourper/Documents/workspace/zhct/zhctproject/ai_api')
assert not RUN.exists();RUN.mkdir(mode=0o700);(RUN/'source').mkdir(mode=0o700)
pins=json.loads((P/'source-frozen-sha.json').read_text())
for n,h in pins['files'].items():
 assert hashlib.sha256((MAIN/n).read_bytes()).hexdigest()==h;src=PRIOR/'source'/n;assert hashlib.sha256(src.read_bytes()).hexdigest()==h;dst=RUN/'source'/n;dst.parent.mkdir(parents=True,exist_ok=True);shutil.copyfile(src,dst)
shutil.copyfile(P/'source-frozen-sha.json',RUN/'source-frozen-sha.json')
for p in (PRIOR).glob('*.php'):
 raw=p.read_text()
 if p.name=='NativePdo.php':
  start=raw.index('final class CoreGate{');end=raw.index('class ReadStatement',start);raw=raw[:start]+"require __DIR__.'/CoreGate.php';\n"+raw[end:];raw=raw.replace('$n<600','$n<800').replace('SQL cap600','SQL cap800')
 if p.name=='app.php':raw=raw.replace('CDXCUSTOMER_WEIGHT_RETEST','CDXFINALWEIGHT')
 if p.name in ['launch.php','run.php']:raw=raw.replace('18973:18974','18975:18976')
 if p.name=='launch.php':raw=raw.replace("'preflight','guard'","'preflight','warm','guard'")
 (RUN/p.name).write_text(raw)
 if p.name in ['NativePdo.php','app.php','launch.php','run.php']:(HERE/'tools'/p.name).write_text(raw)
for p in (HERE/'tools').glob('*.php'):shutil.copyfile(p,RUN/p.name)
for lane in ['B','C']:
 src=PRIOR/f'private-{lane}-final';dst=RUN/f'seed-{lane}';dst.mkdir(mode=0o700)
 for n in ['prepared.json',f'preflight-{lane}.json','prior-persistence.json','sql-budget.jsonl']:
  shutil.copyfile(src/n,dst/n);(dst/n).chmod(0o600)
 e=json.loads((src/'expected.json').read_text())['WEIGHT_RETEST'];(dst/'expected.json').write_text(json.dumps({'WEIGHT_FINAL':e},ensure_ascii=False,indent=2)+'\n')
 c=json.loads((src/'cases.json').read_text())['WEIGHT_RETEST'];c['label']='WEIGHT_FINAL';(dst/'cases.json').write_text(json.dumps({'WEIGHT_FINAL':c},ensure_ascii=False,indent=2)+'\n')
 (dst/'budget-baseline.json').write_text(json.dumps({'old_SQL':len((src/'sql-budget.jsonl').read_text().splitlines()),'old_SQL_SHA':hashlib.sha256((src/'sql-budget.jsonl').read_bytes()).hexdigest(),'old_HTTP':11,'new_HTTP_cap':1})+'\n')
plan={'authorization':'Root exact final Weight: same source GET/date2026-10-11, one HTTP/side, one new token/side cumulative3; initialize constructor/metadata warm at0HTTP before unique GET; cumulative readcap800 no reset;0DMLDDL/SDK; failures stop path', 'label':'WEIGHT_FINAL','method':'GET','path':'/api/user.UserWeight/byDate','query_raw':'date=2026-10-11','actor':{'B':44676,'C':1836},'tenant':10001,'ports':{'B':18975,'C':18976},'source_files':6168,'DML':0,'DDL':0,'old_seals':{'main':'0b3b521b2ce8cee62304ab85d402f2f6fa41c4fd4a82310fa14dc0fb243dd089','failed':'d05e1a1e7f7129f1cf0e34c0d69082b7bbfd4ea1d9fc43f4ac085fbcdb0bffdc'},'metadata_only':'existing same approved schema names frozen once; exact original SHOW/two catalogSELECT/SP_TABLEDEF; unknown data tables and cross-schema metadata denied','original_constructor_models':['Staff','UserWeight','UserWeightStatus','User'],'normal_oracle':'unchanged parent frozen expected.WEIGHT; entire empty data[] contract'}
for dst in [HERE/'machine-plan.json',RUN/'machine-plan.json']:dst.write_text(json.dumps(plan,ensure_ascii=False,indent=2)+'\n')
for lane in ['B','C']:
 entries={p.name:p for p in RUN.iterdir() if p.is_file()};entries.update({p.relative_to(RUN).as_posix():p for p in (RUN/'source').rglob('*') if p.is_file()});entries.update({'private/'+p.name:p for p in (RUN/f'seed-{lane}').iterdir() if p.is_file()});dirs={RUN.name,RUN.name+'/private'}
 for n in entries:dirs.update(str(q) for q in (Path(RUN.name)/n).parents if str(q)!='.')
 target=Path('/tmp/cdx-ai-final-weight-'+lane+'.tar')
 with tarfile.open(target,'w',format=tarfile.USTAR_FORMAT) as t:
  for n in sorted(dirs):i=tarfile.TarInfo(n);i.type=tarfile.DIRTYPE;i.mode=0o700;t.addfile(i)
  for n,p in sorted(entries.items()):raw=p.read_bytes();i=tarfile.TarInfo(RUN.name+'/'+n);i.size=len(raw);i.mode=0o600;t.addfile(i,io.BytesIO(raw))
 target.chmod(0o600)
print(json.dumps({'source_files':6168,'SQL':0,'HTTP':0,'Auth':0}))
