import csv
import json
from pathlib import Path
import shutil
import subprocess
import sys
import time
from preflight import state,sha
R=Path(__file__).parent
sys.path.insert(0,'/workspace/contextra-analytics-runtime-lifecycle-refactor/tools')
from rtsp_test_manager import Manager,DEFAULT_STATE
before=json.loads((R/'before.json').read_text())
assert Manager(R/'registry').containers()==[]
receipt=json.loads(Path('/tmp/codex/ltb1021/2026-09-13_contextra-capture-isolation_r01/approved-input.json').read_text())
assert sha(receipt['path'])=='ff17294be012fd1e89ba9d385717db5771a5b6f1f42bf4ac97ff356e90601812'
default=Manager()
if not (DEFAULT_STATE/'registry.json').exists():
    default.register('sample01',receipt['path'])
assert default.containers()==[]
after=state()
unchanged=before['containers']==after
(R/'after.json').write_text(json.dumps({'time':time.time(),'containers':after,'operating_unchanged':unchanged,
    'default_mapping':default.status(),'disk_free_bytes':shutil.disk_usage('/tmp').free,'task_senders':0},ensure_ascii=False,indent=2))
assert unchanged,'Existing container state changed; inspect before claiming preservation'
rows=[]
for name,path in [('once','once-r03-receive.json'),('continuous1','sample01-continuous.json'),('continuous2','sample02-continuous.json')]:
    data=json.loads((R/path).read_text())
    rows.append({'test':name,**{k:data[k] for k in ['packets','frames','clock_rate','backward_timestamp','sequence_gaps','pts_backwards','elapsed']}})
with (R/'summary.csv').open('w',newline='') as f:
    w=csv.DictWriter(f,fieldnames=rows[0].keys());w.writeheader();w.writerows(rows)
(R/'summary.json').write_text(json.dumps({'results':rows,'actual_concurrent':2,'limit_logic':4,
 'source_gpu':0,'operating_unchanged':unchanged,'cleanup':'PASS','decoded_frame_ai_metadata':'NOT_TESTED',
 'web_sync_absolute_anchor':'NOT_TESTED','h264_hevc_media':'NOT_TESTED'},indent=2))
print('Operating16 containers unchanged; senders0; approved original hash unchanged; default sample01 registered/stopped')
