import json,os,subprocess,time,hashlib,shutil,urllib.request,importlib.util
from pathlib import Path
os.umask(0o077)
module=importlib.util.spec_from_file_location('prior','/tmp/codex/ltb1021/2026-09-20_contextra-fall-ready_r01/prepare.py')
prior=importlib.util.module_from_spec(module);module.loader.exec_module(prior)
cmd,compose,api,inspect,ledger,REPO=prior.cmd,prior.compose,prior.api,prior.inspect,prior.ledger,prior.REPO
HERE=Path(__file__).parent
PRIVATE=Path('/workspace/contextra-runtime-config/pr13-20260923-r01')
def save(name,data,private=False):
    with ((PRIVATE if private else HERE)/name).open('x') as f:json.dump(data,f,indent=2)
def request(path,body,timeout=10,method='POST'):
    r=urllib.request.Request('http://127.0.0.1:35000'+path,data=json.dumps(body).encode(),headers={'Content-Type':'application/json'},method=method)
    with urllib.request.urlopen(r,timeout=timeout) as response:return json.load(response)
if __name__=='__main__':
    PRIVATE.mkdir(mode=0o700)
    containers={}
    for n in cmd(['docker','ps','-a','--format','{{.Names}}']).splitlines():
        c=inspect(n);containers[n]=dict(id=c['Id'],image=c['Image'],started=c['State']['StartedAt'])
    rows=api('/api/v1/streams')['streams']
    save('baseline.json',dict(containers=containers,ledger=ledger(),channels=[{k:r.get(k) for k in ('stream_id','state','child_pid','cleanup_pending')} for r in rows]))
    cfg=json.loads(cmd(compose()+['config','--format','json']))
    save('compose-before.json',cfg,private=True)
    for src,name in [('/workspace/contextra-runtime-config/web-start-candidate-20260918/candidate.env','candidate.env.before'),('/workspace/contextra-runtime-config/metadata-active/compose.yaml','metadata-compose.before'),('/data/contextra/runtime-state/streams_runtime.yaml','streams.before')]:
        shutil.copyfile(src,PRIVATE/name)
    assert shutil.disk_usage('/').free>15*1024**3
    print(json.dumps(dict(channels=len(rows),running=sum(r['state']=='running' for r in rows),image=containers['contextra-analytics-1']['image'])))
