from pathlib import Path
import hashlib,json,shutil
base=Path(__file__).resolve().parent
runtime=Path('/tmp/cdx-ai-core-scan-pay-20261011')
src=Path('/Users/wiscourper/Documents/workspace/zhct/zhctproject/ai_api')
if runtime.exists(): raise SystemExit('Fresh runtime already exists')
runtime.mkdir(mode=0o700)
(runtime/'private').mkdir(mode=0o700)
(runtime/'source').mkdir(mode=0o700)
old=json.loads((base.parent/'parallel-ai-investigate-write3-20261011/source-frozen-sha.json').read_text())['files']
roots=sorted(set(n.split('/')[0] for n in old))
files={}
for name in roots:
    p=src/name
    if p.is_symlink(): raise SystemExit('Source symlink '+name)
    if p.is_dir(): shutil.copytree(p,runtime/'source'/name,symlinks=False)
    elif p.is_file(): shutil.copy2(p,runtime/'source'/name)
for p in sorted((runtime/'source').rglob('*')):
    if p.is_file():
        name=p.relative_to(runtime/'source').as_posix()
        files[name]=hashlib.sha256(p.read_bytes()).hexdigest()
        if hashlib.sha256((src/name).read_bytes()).hexdigest()!=files[name]: raise SystemExit('Source drift during clone '+name)
out={'source_root':str(src),'HEAD':'bb530e9b78894faa0f83d0d92416a152a468b1c2','roots':roots,'files':files,'count':len(files),'old_count':len(old),'deltas_from_old':{n:{'old':old.get(n),'current':h} for n,h in files.items() if old.get(n)!=h},'all_source_clone':True}
raw=json.dumps(out,ensure_ascii=False,indent=2)+'\n'
(base/'source-frozen-sha.json').write_text(raw)
(runtime/'source-frozen-sha.json').write_text(raw)
prior=Path('/tmp/cdx-ai-core-read-preflight-20261011')
for n in ['probe.php','collision.php','protection.php','typed-prepare-plan.json']:
    shutil.copy2(prior/n,runtime/n)
assert hashlib.sha256((runtime/'typed-prepare-plan.json').read_bytes()).hexdigest()=='50a7b2dba60b68b81aa6685676fdfb821da9441207d47108541e7a722321262a'
print(json.dumps({'clone_files':len(files),'old_files':len(old),'deltas':list(out['deltas_from_old']),'runtime':str(runtime)}))
