import hashlib
import importlib.util
import json
import os
from pathlib import Path
import shutil
import sys
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={'rtsp-test-source-02':'web-cam08-test','rtsp-test-source-03':'web-cam01-test'}
preset=Path('/workspace/contextra-runtime-config/test-run/presets/web-cam01.yaml')

def start():
    assert not (R/'plan.json').exists()
    manifest=json.loads(Path('/tmp/codex/ltb1021/2026-09-15_contextra-tracking-off_r01/closeout.json').read_text())
    assert all(p.sha(p.REPO/x['path'])==x['content_sha256'] for x in manifest['paths'])
    states={src:p.prior.state(sid) for src,sid in channels.items()}
    assert states['rtsp-test-source-02']['state']=='running'
    assert states['rtsp-test-source-03']['state']=='stopped'
    settings={src:p.api('/api/v1/streams/'+sid+'/settings') for src,sid in channels.items()}
    assert settings['rtsp-test-source-02']['effective']['tracking']['enabled'] is False
    assert settings['rtsp-test-source-02']['effective']['intrusion']['enabled'] is False
    shutil.copy2(preset,R/'preset.before')
    p.save('plan.json',dict(states=states,settings=settings,preset_hash=p.sha(preset),inventory=p.base.inventory(),
        sender=p.prior.ops.prior.prev.sender(),head=p.cmd(['git','rev-parse','HEAD']).strip(),
        limits=dict(window_seconds=24,first_frame_seconds=90,helper_seconds=180,minimum_ram_gib=4,analytics_ram_gib=12),
        restore='Only03 started by this task; preserve02 run/settings and all senders. No repeat Start.'))
    data=yaml.safe_load(preset.read_text());assert data['camera']['stream_id']==channels['rtsp-test-source-03']
    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.sha(preset))
    p.ledger('start03_via_cli',at_monotonic=time.monotonic())
    p.cmd(['python3',str(p.REPO/'tools/test_run.py'),'start',str(preset)],timeout=110)
    assert p.prior.state(channels['rtsp-test-source-02'])['run_id']==states['rtsp-test-source-02']['run_id']
    print('Commit12 hashes match;03 started;02 run preserved')

def observe():
    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('two-off',channels,24)
    plan=p.read('plan.json');data=p.read('two-off.json');summary=p.read('two-off-summary.json')
    states={src:p.prior.state(sid) for src,sid in channels.items()}
    assert states['rtsp-test-source-02']['run_id']==plan['states']['rtsp-test-source-02']['run_id']
    assert p.base.inventory()==plan['inventory']
    assert p.prior.ops.prior.prev.sender()['executionId']==plan['sender']['executionId']
    result={}
    for src,sid in channels.items():
        view=p.api('/api/v1/streams/'+sid+'/settings')
        assert view['effective']['tracking']['enabled'] is False and view['effective']['intrusion']['enabled'] is False
        assert states[src]['state']=='running' and not states[src]['metadata_path']['performance']['detail']
        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]
        result[src]=dict(state=states[src]['state'],fps=v['fps'],redis_fps=v['redis_fps'],queue_range=[min(v['queue']),max(v['queue'])],delta=v['counter_delta'],null_track_ids=True,scenario_off=True)
    p.save('final.json',result);print(json.dumps(result))

if __name__=='__main__':
    {'start':start,'observe':observe}[sys.argv[1]]()
