import hashlib
import json
from pathlib import Path
import subprocess
import time

R = Path(__file__).parent
def cmd(args):
    return subprocess.check_output(args, text=True).strip()
def sha(path):
    h = hashlib.sha256()
    with Path(path).open('rb') as f:
        for block in iter(lambda: f.read(1024*1024), b''):
            h.update(block)
    return h.hexdigest()
def state():
    ids = cmd(['docker','ps','-aq']).split()
    result = json.loads(cmd(['docker','inspect',*ids]))
    return {x['Name']: {'id':x['Id'], 'image':x['Image'], 'started':x['State']['StartedAt'],
            'running':x['State']['Running'], 'restart':x['HostConfig']['RestartPolicy'],
            'config_hash':hashlib.sha256(json.dumps(x['Config'],sort_keys=True).encode()).hexdigest()}
            for x in result if not x['Name'].startswith('/contextra-rtsp-')}
if __name__ == '__main__':
    approved=json.loads(Path('/tmp/codex/ltb1021/2026-09-13_contextra-capture-isolation_r01/approved-input.json').read_text())
    print('receipt keys',list(approved))
    snapshot={'time':time.time(),'containers':state(), 'limits':{'source_minutes':20,'runtime_minutes':35,
       'sender_cpu':1,'sender_memory_mib':512,'max_senders':4,'test_seconds':60,'gpu':0,
       'log_mib_per_container':1,'receiver_seconds':15,'same_failure_stop':2}}
    (R/'before.json').write_text(json.dumps(snapshot,indent=2))
    print('preflight saved; containers',len(snapshot['containers']))
