import hashlib
import importlib.util
import json
import os
from pathlib import Path
import time

os.umask(0o077)
R=Path(__file__).parent
s=importlib.util.spec_from_file_location('comparison','/tmp/codex/ltb1021/2026-09-15_contextra-channel-compare_r01/compare.py')
p=importlib.util.module_from_spec(s);s.loader.exec_module(p);p.R=R
plan=p.read('plan.json')
states=p.api('/api/v1/streams')['streams']
ids=['rtsp-test-01','web-cam08-test','web-cam01-test']
settings={src:p.api('/api/v1/streams/'+sid+'/settings') for src,sid in zip(plan['settings'],ids)}
assert settings==plan['settings']
for sid in ids:
    q=next(q for q in states if q['stream_id']==sid)
    before=next(q for q in plan['states'] if q['stream_id']==sid)
    assert q['run_id']==before['run_id'] and q['state']=='running'
    assert not q['metadata_path']['performance']['detail'] and q['metadata_path']['visual'] is None
analytics=p.ops.base.inspect('contextra-analytics-1')
assert analytics['Id']==plan['analytics']['Id'] and analytics['Image']==plan['analytics']['Image']
assert p.ops.base.g.sha(p.REG)==plan['registry_hash']
publisher=p.api('/api/v1/metadata/status')['metrics']
assert publisher['workers']==3 and not publisher['profile']['enabled'] and not publisher['workerErrors']
failed=next(q for q in states if q['stream_id']=='tmp16c-2135-g2-c4')
assert failed['desired_state']=='stopped' and failed['state']=='error' and not failed['cleanup_pending']
assert failed['last_cleanup']['completed'] and failed['last_cleanup']['generation']==failed['run_generation']
assert failed['cleanup_error'] is None
root=Path('/workspace/contextra-analytics-runtime-lifecycle-refactor')
files=['app/start_diagnostics.py','app/stream_manager.py','tests/test_start_diagnostics.py']
p.save('final-checks.json',dict(at=time.time(),states=states,publisher=publisher,settings_preserved=True,
    analytics_id_unchanged=True,registry_hash_preserved=True,
    sender=p.ops.prior.prev.sender(),inventory=p.ops.base.inventory(),
    source_hashes={f:hashlib.sha256((root/f).read_bytes()).hexdigest() for f in files},
    source_only=True,build=0,start=0,stop=0,delete=0))
print('Final: same3 running, detail/capture Off; failed registration cleanup complete/error retained; workers3/control1; no lifecycle mutation')
