from probe import *
import shutil

assert not (R/'swap-started.json').exists()
fixed=json.loads((R/'fixed/diag-result.json').read_text())
text=(R/'fixed/diag-rx.log').read_text()
counts=re.findall(r'(\d+) frames decoded; (\d+) decode errors',text)
assert fixed['returncode']==0 and counts and int(counts[-1][0])>=20 and int(counts[-1][1])==0
save('fixed-decode-verdict.json',dict(decoded=int(counts[-1][0]),decode_errors=0,output_frames=20,returncode=0))
plan=json.loads((R/'plan.json').read_text());current=prev.sender()
assert current['executionId']==plan['sender']['executionId']
assert not ops.inspect('contextra-analytics-1')['State']['Running']
registry=Manager().root/'registry.json'
save('swap-started.json',dict(at=time.time(),reason='Reproduced shared pipe seek poisoning and validated live/nonseekable fix; approved replacement',before=current,source_hash=ops.g.sha(ops.REPO/'tools/rtsp_test_worker.py'),clock_hash=ops.g.sha(ops.REPO/'tools/rtsp_test_time.py'),restore='Restore old worker bytes from fixed HEAD backup only if needed; same H264 mapping; fresh execution always requires new Anchor. Do not auto-restart failing source.'))
(R/'worker.before.py').write_bytes(subprocess.check_output(['git','show','HEAD:tools/rtsp_test_worker.py'],cwd=ops.REPO))
if registry.exists():shutil.copy2(registry,R/'registry.before.json')
manager=Manager();stopped=manager.stop('sample01');save('swap-stopped.json',stopped)
new=manager.start('sample01',mode='continuous')
deadline=time.monotonic()+12
while time.monotonic()<deadline:
    now=prev.sender()
    if now['state']=='STREAMING' and now['anchor']:break
    time.sleep(.3)
else:raise RuntimeError('NEW_SENDER_NO_ANCHOR')
assert now['uri']==current['uri'] and now['video']==current['video']
save('swap-result.json',dict(at=time.time(),sender=now,source_hash=ops.g.sha(ops.REPO/'tools/rtsp_test_worker.py'),clock_hash=ops.g.sha(ops.REPO/'tools/rtsp_test_time.py')))
ledger=json.loads((R/'ledger.json').read_text());ledger['sender_restart']=1;save('ledger.json',ledger)
print('PASS: approved sample01 replacement; same URI/input; new execution/RTCP Anchor')
