import hashlib
import importlib.util
import json
import os
from pathlib import Path
import shutil
import subprocess
import time
import urllib.request

os.umask(0o077)
spec=importlib.util.spec_from_file_location('prior_ops','/tmp/codex/ltb1021/2026-09-20_contextra-fall-ready_r01/prepare.py')
prior=importlib.util.module_from_spec(spec);spec.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/pr12-demo-20260921-r01')

def save(name,data,private=False):
    path=(PRIVATE if private else HERE)/name
    with path.open('x') as f:json.dump(data,f,indent=2)

def request(path,body,method='POST',timeout=10):
    req=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(req,timeout=timeout) as response:return json.load(response)

def no_channels():
    rows=api('/api/v1/streams')['streams']
    assert all(r['state']=='stopped' and not r.get('child_pid') and not r.get('cleanup_pending') for r in rows)
    return rows

if __name__=='__main__':
    PRIVATE.mkdir(mode=0o700)
    assert cmd(['git','-C',str(REPO),'rev-parse','HEAD']).strip()=='640acd4254191e3449f086868563379937d8a006'
    assert shutil.disk_usage('/').free>15*1024**3
    before={}
    for name in cmd(['docker','ps','-a','--format','{{.Names}}']).splitlines():
        c=inspect(name);before[name]=dict(id=c['Id'],image=c['Image'],started=c['State']['StartedAt'])
    cfg=json.loads(cmd(compose()+['config','--format','json']))
    assert cfg['services']['analytics']['image']==before['contextra-analytics-1']['image']
    assert cfg['services']['analytics']['environment']['CONTEXTRA_EVENT_ARTIFACT_ENABLED']=='1'
    assert cfg['services']['analytics']['environment']['CONTEXTRA_ARTIFACT_HTTP_ENABLED']=='1'
    save('containers-before.json',before)
    save('compose-before.json',cfg,private=True)
    for source,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_runtime.before')]:
        shutil.copyfile(source,PRIVATE/name)
    rows=api('/api/v1/streams')['streams'];settings={}
    for row in rows:settings[row['stream_id']]=api('/api/v1/streams/'+row['stream_id']+'/settings')['configured']
    save('settings-before.json',settings,private=True)
    save('preflight.json',dict(channels=len(rows),running=[r['stream_id'] for r in rows if r['state']=='running'],
         artifacts={k:api('/api/v1/metadata/status')['artifacts'][k] for k in ('enabled','http_enabled')},root_free=shutil.disk_usage('/').free))
    print(json.dumps(dict(channels=len(rows),running=sum(r['state']=='running' for r in rows),base_image=before['contextra-analytics-1']['image'])))
