import hashlib
import json
import os
import pathlib
import subprocess
import sys

os.umask(0o077)
R=pathlib.Path(__file__).parent;R.chmod(0o700)
mode=sys.argv[1]
assert mode in ('before','after') and not (R/(mode+'.json')).exists()
repo=pathlib.Path('/workspace/contextra-analytics-runtime-lifecycle-refactor')
ssims=pathlib.Path('/workspace/ssims.ai/fastapi/gstreamer-python/ai_engine/byte_tracker.py')
image='sha256:46f5c223b6e2de940dc275cdfcf4bcfe247abdbae55f91d024bcb301bb9dd08d'
name='codex-tracking-compare-'+mode
cmd=['docker','run','--rm','--pull','never','--runtime','runc','--network','none','--name',name,
     '--cpus','2','--memory','4g','--memory-swap','4g','--cap-drop','MKNOD','-e','NVIDIA_VISIBLE_DEVICES=void',
     '-e','OPENBLAS_NUM_THREADS=1','-e','PYTHONDONTWRITEBYTECODE=1','-e','PYTHONPATH=/source:/opt/contextra',
     '--mount',f'type=bind,src={repo},dst=/source,readonly',
     '--mount',f'type=bind,src={ssims},dst=/ssims/byte_tracker.py,readonly',
     '--mount',f'type=bind,src={R},dst=/evidence','--entrypoint','timeout',image,'90s','python3','/evidence/bench.py',mode]
before=subprocess.check_output(['docker','inspect','--format','{{.Id}} {{.Image}} {{.State.Status}}','contextra-analytics-1'],text=True)
(R/(mode+'-ledger.json')).write_text(json.dumps({'started_utc':'2026-09-13T02:41:45Z','mode':mode,
    'image':image,'cpu':2,'memory_gib':4,'timeout_s':90,'model_loads':0,'rtsp_runs':0,
    'ssims_source_hash':hashlib.sha256(ssims.read_bytes()).hexdigest(),
    'source_hash':hashlib.sha256((repo/'app/byte_tracking.py').read_bytes()).hexdigest()},indent=2))
try:
    p=subprocess.run(cmd,capture_output=True,text=True,timeout=110)
    (R/(mode+'.log')).write_text(p.stdout+p.stderr)
    print(p.stdout[-7000:]);print('exit',p.returncode)
    assert p.returncode==0
finally:
    subprocess.run(['docker','rm','-f',name],capture_output=True,timeout=10)
    after=subprocess.check_output(['docker','inspect','--format','{{.Id}} {{.Image}} {{.State.Status}}','contextra-analytics-1'],text=True)
    assert before==after
