import importlib.util,json,os,shutil,urllib.request
from pathlib import Path
os.umask(0o077)
R=Path(__file__).parent
s=importlib.util.spec_from_file_location('gate','/tmp/codex/ltb1021/2026-09-11_service-stop_r01/gate.py')
g=importlib.util.module_from_spec(s);s.loader.exec_module(g)
HEAD='3a883f29c32db6a8b96c62b1474c614fb4f9ae61'
if __name__=='__main__':
    assert not (R/'plan.json').exists()
    assert g.sh(['git','-C',str(g.REPO),'rev-parse','HEAD']).strip()==HEAD
    c=g.inspect();assert c['State']['Health']['Status']=='healthy'
    env=g.load_env_file(str(g.ENV));overlay=Path(env['CONTEXTRA_RUNTIME_STATE_ROOT'])/'streams_runtime.yaml'
    active=g.ENV.parent/'metadata-active/compose.yaml'
    op=urllib.request.build_opener(urllib.request.ProxyHandler({}))
    with op.open('http://127.0.0.1:'+env['FASTAPI_HOST_PORT']+'/api/v1/streams',timeout=3) as f: streams=json.load(f)['streams']
    assert len(streams)==1 and streams[0]['state']=='stopped'
    root=g.sh(['docker','info','--format','{{.DockerRootDir}}']).strip();free=shutil.disk_usage(root).free;assert free>=15*1024**3
    art=Path('/data/contextra/model-artifacts/builds/fire-smoke-193-20260913-r01')
    assert g.sha(art/'model.plan')=='689f6286712264376e8eaa2443a4a3971ed07dd1667c3a4b0ff8b806e1003700'
    for name,path in [('env.before',g.ENV),('overlay.before',overlay),('active-compose.before',active)]: (R/name).write_bytes(path.read_bytes())
    mounts={str(Path(m['Source'])/p):g.sha(Path(m['Source'])/p) for m in c['Mounts'] if m['Destination'].endswith('RFDETRKeypointPreview') for p in ('config.pbtxt','2/model.plan')}
    plan=dict(started_utc='2026-09-14T01:50:54Z',head=HEAD,analytics=c,controls=str(active.parent),other_containers=g.others(),gpu_mib=g.gpu(),disk_free=free,env_hash=g.sha(g.ENV),overlay=str(overlay),overlay_hash=g.sha(overlay),active_hash=g.sha(active),config_hash=g.sha(g.CFG),plan_hash=g.sha(g.CFG.parent/'2/model.plan'),pose_hashes=mounts,fire_plan_hash=g.sha(art/'model.plan'),failures=0,build_count=0,start_count=0)
    (R/'plan.json').write_text(json.dumps(plan,indent=2))
    (R/'budget.json').write_text(json.dumps(dict(started_at='2026-09-14T01:50:54Z',failed_groups=0,groups=[]),indent=2))
    print(json.dumps(dict(healthy=True,stopped=True,disk_gib=round(free/1024**3,1),gpu_mib=plan['gpu_mib'])))
