import hashlib
import json
import os
from pathlib import Path
import shlex
import shutil
import subprocess
import urllib.request

os.umask(0o077)
root = Path('/workspace/contextra-analytics-runtime-lifecycle-refactor')
evidence = Path('/tmp/codex/ltb1021/20260909-identity-retry')
rollback = 'sha256:fc7ab200686839877989c7ea2c05426c6079377b4f4dc8448a29d068df054d8f'
def call(args):
    return subprocess.check_output(args, text=True, stderr=subprocess.PIPE).strip()
env = {}
for line in Path('/workspace/contextra-runtime-config/runtime.env').read_text().splitlines():
    if line and not line.lstrip().startswith('#') and '=' in line:
        key, value = line.split('=', 1)
        env[key.strip()] = value.strip().strip('"\'')
assert env['CONTEXTRA_IMAGE'] == 'contextra-analytics:smoke-be367b7', 'env CAS mismatch'
assert call(['git','-C',str(root),'rev-parse','HEAD']) == 'b3868cfe2d1287ecb49296e6119174fa2b9036e8'
assert not call(['git','-C',str(root),'status','--porcelain'])
assert call(['docker','image','inspect',env['CONTEXTRA_IMAGE'],'--format','{{.Id}}']) == rollback
collision = subprocess.run(['docker','image','inspect','contextra-analytics:smoke-b3868cf'],stdout=subprocess.DEVNULL,stderr=subprocess.DEVNULL)
assert collision.returncode != 0, 'tag collision'
assert shutil.disk_usage('/var/lib/docker').free >= 25 * 1024**3
for row in call(['ps','-eo','comm=,args=']).splitlines():
    parts = row.split(None, 1)
    if len(parts) == 2 and (parts[0] == 'docker' or parts[0].startswith('docker-build')):
        argv = shlex.split(parts[1])
        assert not any(x in argv for x in ('build','pull','bake')), 'active build/pull'
baseline = {}
analytics = None
fmt = '{{json .Name}} {{json .Id}} {{json .Image}} {{.RestartCount}} {{.State.OOMKilled}} {{.State.Status}} {{if index .State "Health"}}{{.State.Health.Status}}{{else}}none{{end}}'
for cid in call(['docker','ps','-aq']).splitlines():
    data = shlex.split(call(['docker','inspect','--format',fmt,cid]))
    name, identifier, image, restarts, oom, status, health = data
    record = {'id':identifier,'image':image,'restart':int(restarts),'oom':oom,'status':status,'health':health}
    if name == '/contextra-analytics-1':
        analytics = record
    else:
        baseline[hashlib.sha256(name.encode()).hexdigest()] = record
    if name in ('/contextra-analytics-1','/contextra-postgresql-1','/contextra-redis-1'):
        assert status == 'running' and health == 'healthy', 'service not healthy'
assert analytics and analytics['image'] == rollback
port = int(env['FASTAPI_HOST_PORT'])
with urllib.request.urlopen(f'http://127.0.0.1:{port}/api/v1/streams', timeout=10) as response:
    streams = json.load(response)['streams']
if isinstance(streams, dict):
    streams = list(streams.values())
assert len(streams) == 1, 'unexpected stream count'
assert all(s.get('state') == 'stopped' and s.get('desired_state') == 'stopped'
           and s.get('observed_state') == 'stopped' for s in streams), 'stream not stopped'
(evidence/'baseline.json').write_text(json.dumps({'protected':baseline,'analytics':analytics,'stream_count':len(streams),'port':port},indent=2))
print(json.dumps({'gate':'PASS','protected_containers':len(baseline),'stream_count':len(streams),'stopped':True,'free_gib':round(shutil.disk_usage('/').free/1024**3,1)}))
