import importlib.util
import json
import os
import pathlib
import runpy
import shutil
import subprocess
import sys
os.umask(0o077)
OLD=pathlib.Path('/tmp/codex/ltb1021/2026-09-10_contextra-det-window_r01')
spec=importlib.util.spec_from_file_location('gate',OLD/'gate.py')
g=importlib.util.module_from_spec(spec);sys.modules['gate']=g;spec.loader.exec_module(g)
g.R=pathlib.Path(__file__).parent
g.HEAD='43e1923a67de47ad4b8d64806853e5f8ad0b158e'
g.TAG='contextra-analytics:start-window-43e1923'

def gate():
    assert not (g.R/'gate.json').exists()
    assert g.shell(['git','-C',str(g.REPO),'rev-parse','HEAD']).strip()==g.HEAD
    assert not g.shell(['git','-C',str(g.REPO),'status','--porcelain']).strip()
    docker_root=g.shell(['docker','info','--format','{{.DockerRootDir}}']).strip()
    free=min(shutil.disk_usage('/').free,shutil.disk_usage(docker_root).free)
    assert free>=15*1024**3
    assert subprocess.run(['pgrep','-f',r'(^|/)docker (build|buildx build|pull)'],capture_output=True).returncode==1
    assert subprocess.run(['docker','image','inspect',g.TAG],capture_output=True).returncode!=0
    data=g.inspect_all();c=next(x for x in data if x['Name']=='/contextra-analytics-1')
    assert c['State']['Status']=='exited' and not c['State']['OOMKilled'] and c['RestartCount']==0
    assert c['Image']=='sha256:92a87856fcb5a541dd1c630e49eb7ded3a2ac36eb93da6a346638ac9d0441e12'
    env=g.load_env_file(str(g.ENV))
    assert env['CONTEXTRA_IMAGE']=='contextra-analytics:det-window-99698a0'
    assert g.sha(g.CFG)=='5e5a4d22786f8b5218ac821379fbec091d9e3006f62c880ee3e3da5ced2f0e0b'
    assert g.sha(g.CFG.parent/'2/model.plan')=='5fdf1e9c55ab947a3b7d5f7f6bdceaf1e36a9e52efdf86f5a15d3b99b8631d1e'
    overlay=pathlib.Path(env['CONTEXTRA_RUNTIME_STATE_ROOT'])/'streams_runtime.yaml'
    specs=g.yaml.safe_load(overlay.read_text())['added'];assert len(specs)==1
    s=specs[0]
    assert all(s[x] is False for x in ['store','active_learning','autostart']) and s['scenarios']=='off'
    assert s['inference_profile']['roles']==['det'] and s['inference_profile']['det_model']=='RFDETRMedium'
    g.validate_deployment_inputs(str(g.ENV))
    gpu=int(g.shell(['nvidia-smi','--id=0','--query-gpu=memory.used','--format=csv,noheader,nounits']).strip())
    assert gpu<16384
    out=dict(status='PASS',head=g.HEAD,tag=g.TAG,env_hash=g.sha(g.ENV),config_hash=g.sha(g.CFG),
             overlay_hash=g.sha(overlay),plan_hash=g.sha(g.CFG.parent/'2/model.plan'),old_image=c['Image'],
             old_tag=env['CONTEXTRA_IMAGE'],other_containers=g.other_baseline(data),
             disk_free_bytes=free,gpu_used_mib=gpu,docker_on_root=os.stat(docker_root).st_dev==os.stat('/').st_dev)
    (g.R/'gate.json').write_text(json.dumps(out,indent=2))
    print(json.dumps({k:v for k,v in out.items() if k!='other_containers'}))

if __name__=='__main__':
    if sys.argv[1]=='gate':gate()
    elif sys.argv[1]=='build':runpy.run_path(str(OLD/'build.py'),run_name='__main__')
    elif sys.argv[1]=='verify':runpy.run_path(str(OLD/'verify_image.py'),run_name='__main__')
