"""Fresh byte-only source and tool seed. No HTTP or SQL; never touches old assets."""
from pathlib import Path
import hashlib, json, shutil, subprocess

HERE = Path(__file__).resolve().parent
OLD = HERE.parent / 'parallel-ai-core-scan-pay-20261011'
PRIOR = Path('/tmp/cdx-ai-core-scan-pay-20261011')
RUN = Path('/tmp/cdx-ai-core-direct002-20261011')
MAIN = Path('/Users/wiscourper/Documents/workspace/zhct/zhctproject/ai_api')
pins = json.loads((OLD / 'source-frozen-sha.json').read_text())
assert not RUN.exists(), 'Fresh runtime collision'
assert subprocess.check_output(['git','-C',str(MAIN),'rev-parse','HEAD'],text=True).strip() == pins['HEAD']
RUN.mkdir(mode=0o700)
(RUN/'source').mkdir(mode=0o700)
(HERE/'tools').mkdir()
for name, digest in pins['files'].items():
    src = MAIN/name
    assert src.is_file() and not src.is_symlink() and not any(x.startswith('._') for x in src.parts)
    assert hashlib.sha256(src.read_bytes()).hexdigest() == digest, name
    target = RUN/'source'/name
    target.parent.mkdir(parents=True,exist_ok=True)
    shutil.copyfile(src,target)  # bytes only: no modes, xattrs, resource forks or AppleDouble
    assert hashlib.sha256(target.read_bytes()).hexdigest() == digest
actual = {p.relative_to(RUN/'source').as_posix() for p in (RUN/'source').rglob('*') if p.is_file()}
assert actual == set(pins['files']) and len(actual)==6168
newpins = dict(pins, bytecopy=True, apple_double=0, actual_fileset_exact=True)
for dst in [HERE/'source-frozen-sha.json',RUN/'source-frozen-sha.json']:
    dst.write_text(json.dumps(newpins,ensure_ascii=False,indent=2)+'\n')
for name in ['app.php','native.php','NativePdo.php','launch.php','decimal-oracle.php','datetime-oracle.php','physical-money.php','cleanup.php','cleanup-cache.php']:
    raw = (OLD/'tools'/name).read_text()
    if name=='NativePdo.php':
        raw=raw.replace('0.01','0.02').replace('0.99','0.97').replace('CDXCORE11S1_DIRECT','CDXCORE11S1_DIRECT_002')
        raw=raw.replace("['PREPAY_FIRST','PREPAY_FIRST_RETRY','PREPAY_FIRST_RETRY1','DIRECT_SUCCESS','DIRECT_SUCCESS_RETRY1','DIRECT_SUCCESS_RETRY2']","['DIRECT_002']")
        raw=raw.replace("public static $scenario='';","public static $total=0;public static $scenario='';")
        raw=raw.replace("$kind=CoreGate::kind($this->db,$this->queryString);$r=", "$kind=CoreGate::kind($this->db,$this->queryString);ck(++CoreGate::$total<=(getenv('CORE_LANE')==='B'?80:160),'Exact business native SQL cap');$r=")
    if name=='native.php':
        raw=raw.replace("function sourceProof(){global $root;", "function sourceProof(){global $root;$actual=[];foreach(new RecursiveIteratorIterator(new RecursiveDirectoryIterator($root,FilesystemIterator::SKIP_DOTS)) as $p){ck(!$p->isLink(),'No source symlinks');if($p->isFile()){ck(strpos($p->getBasename(),'._')!==0&&bin2hex(file_get_contents($p->getPathname(),false,null,0,4))!=='00051607','No AppleDouble file/magic');$actual[]=substr($p->getPathname(),strlen($root)+1);}}sort($actual);")
        raw=raw.replace("foreach($pins as $n=>$h)ck", "$names=array_keys($pins);sort($names);ck($actual===$names&&count($actual)===6168,'Actual whole source file-set exact6168');foreach($pins as $n=>$h)ck")
        raw=raw.replace("$s=nativePdo($db)->prepare($sql);$bind=[];", "$s=nativePdo($db)->prepare($sql);$bind=[];")
    if name=='launch.php':
        start=raw.index("!in_array($stage,[")
        end=raw.index("],true))exit(78)",start)
        raw=raw[:start]+"!in_array($stage,['preflight','guard','run','capture','physical-money','cleanup','cleanup-cache','test-observer','test-gate','start','stop'"+raw[end:]
        raw=raw.replace('18941:18942','18943:18944')
        raw=raw.replace("['guard','guard-fresh','renew-auth','renew-auth-second','renew-auth-third']", "['guard']")
    for dest in [HERE/'tools'/name,RUN/name]: dest.write_text(raw)
for lane in ['B','C']:
    dst=RUN/f'seed-{lane}'
    dst.mkdir(mode=0o700)
    old=PRIOR/f'private-{lane}-final'
    for srcname,dstname in [('prepared.json','prepared.json'),(f'preflight-{lane}.json',f'preflight-{lane}.json'),('persistence-final.json','prior-persistence.json'),('guard.json','prior-guard.json')]:
        shutil.copyfile(old/srcname,dst/dstname)
        (dst/dstname).chmod(0o600)
plan={
 'authorization':'RUNNING-20261011-0926.md exact new vector',
 'method':'POST','path':'/api/mealCheckout/directPay','case':'DIRECT_002',
 'money':{'value':'0.02','php_type':'string'},'remark':'CDXCORE11S1_DIRECT_002',
 'tenant':2147001111,'platform':'POC','host':'core.scan-pay.invalid',
 'lanes':{'B':{'AI_U1':46916,'STORE_U1':99689,'STORE_S1':108602,'STORE_R1':78,'port':18943,'native_cap':80},'C':{'AI_U1':1931,'STORE_U1':2792,'STORE_S1':2215,'STORE_R1':13,'port':18944,'native_cap':160}},
 'each_lane':{'HTTP':1,'INSERT':3,'UPDATE':3,'affected_each':1,'preflight_SELECT_cap':160,'token_U1_max':1,'prepare_DML':0,'DELETE':0,'DDL':0,'refund':0,'external_HTTP':0,'retry':0},
 'expected':{'balance':'0.97','gift':'0.00','pay_money':'0.03','log_money':'-0.02','log_after':'0.97','order_amount':'0.02','settlement_amount':'0.02','status':20,'order_status':30,'deduction_order':['gift','subsidy','cash']},
 'old_manifest':'cfda90d3fb84df1c73920f7b831c64d85e28bdfbd4a4b965086fe05a96d57b15',
 'old_success_no_replay':True,'source_files':6168,'source_HEAD':pins['HEAD']}
(HERE/'machine-plan.json').write_text(json.dumps(plan,ensure_ascii=False,indent=2)+'\n')
(RUN/'machine-plan.json').write_text(json.dumps(plan,ensure_ascii=False,indent=2)+'\n')
exemplars={}
for lane,label in [('B','DIRECT_SUCCESS_RETRY2'),('C','DIRECT_SUCCESS_RETRY1')]:
    events=[json.loads(s) for s in (PRIOR/f'private-{lane}-final/business-native.jsonl').read_text().splitlines()]
    exemplars[lane]=[e for e in events if e['scenario']==label and e['layer']=='original framework bind plan' and e['queryString'].lstrip().startswith(('INSERT','UPDATE'))]
    assert len(exemplars[lane])==6
(HERE/'exact-prior-SQL-bind-exemplars.json').write_text(json.dumps(exemplars,ensure_ascii=False,indent=2)+'\n')
print(json.dumps({'source_files':len(actual),'bytecopy':True,'HTTP':0,'SQL':0,'runtime':str(RUN)}))
