import importlib.util
import json
import os
from pathlib import Path
import shutil
import time
import yaml

os.umask(0o077)
R=Path(__file__).parent
s=importlib.util.spec_from_file_location('ops','/tmp/codex/ltb1021/2026-09-15_contextra-tracking-off_r01/ops.py')
o=importlib.util.module_from_spec(s);s.loader.exec_module(o);p=o.p;p.R=R
channels=p.CHANNELS
assert not (R/'plan.json').exists()
states={src:p.prior.state(sid) for src,sid in channels.items()}
assert states['rtsp-test-source-01']['state']=='stopped'
assert all(q['state']=='running' for src,q in states.items() if src!='rtsp-test-source-01')
preset=Path('/workspace/contextra-runtime-config/test-run/presets/intrusion-demo.yaml')
data=yaml.safe_load(preset.read_text());assert data['camera']['stream_id']=='rtsp-test-01'
settings={src:p.api('/api/v1/streams/'+sid+'/settings') for src,sid in channels.items()}
assert all(not v['effective']['tracking']['enabled'] and not v['effective']['intrusion']['enabled'] for src,v in settings.items() if src!='rtsp-test-source-01')
shutil.copy2(preset,R/'preset.before')
sender=p.prior.ops.prior.prev.sender();inventory=p.base.inventory()
p.save('plan.json',dict(states=states,settings=settings,preset_hash=p.sha(preset),inventory=inventory,sender=sender,
    limits=dict(window_seconds=24,first_frame_seconds=90,helper_seconds=180,minimum_ram_gib=4,analytics_ram_gib=12),
    restore='Only01 is started here;02/03 preserved, no repeated Start or sender change.'))
data.setdefault('settings',{})['tracking']={'enabled':False}
data['settings'].setdefault('intrusion',{})['enabled']=False;data['debug_metrics']=False
p.atomic(preset,yaml.safe_dump(data,sort_keys=False,allow_unicode=True).encode(),p.read('plan.json')['preset_hash'])
p.ledger('start01_via_cli')
p.cmd(['python3',str(p.REPO/'tools/test_run.py'),'start',str(preset)],timeout=110)
print('01 started;02/03 preserved',flush=True)
s=importlib.util.spec_from_file_location('window','/tmp/codex/ltb1021/2026-09-15_contextra-three-channel_r01/observe.py')
w=importlib.util.module_from_spec(s);s.loader.exec_module(w);w.R=R;w.p.R=R
time.sleep(5);w.window('three-off',channels,24)
out={};summary=p.read('three-off-summary.json');data=p.read('three-off.json')
for src,sid in channels.items():
    st=p.prior.state(sid);view=p.api('/api/v1/streams/'+sid+'/settings')
    assert st['state']=='running' and not st['metadata_path']['performance']['detail']
    assert not view['effective']['tracking']['enabled'] and not view['effective']['intrusion']['enabled']
    if src!='rtsp-test-source-01':
        assert st['run_id']==states[src]['run_id'] and view['configured']==settings[src]['configured']
    frames=[x['channels'][src]['redis']['frame'] for x in data['samples']]
    assert all(obj['trackId'] is None for f in frames for obj in f['objects'])
    assert all(not f.get('events') and not f.get('scenarioConfig') for f in frames)
    v=summary[src];out[src]=dict(state=st['state'],fps=v['fps'],redis_fps=v['redis_fps'],queue=[min(v['queue']),max(v['queue'])],delta=v['counter_delta'],durations=v['durations'])
assert p.base.inventory()==inventory and p.prior.ops.prior.prev.sender()['executionId']==sender['executionId']
p.save('final.json',out)
print(json.dumps({src:{k:v for k,v in d.items() if k!='durations'} for src,d in out.items()}))
