from ops import *
import resource,yaml
specs=yaml.safe_load(Path('/data/contextra/runtime-state/streams_runtime.yaml').read_text())['added']
s=next(s for s in specs if str(s.get('source_id'))=='3')
assert api('/api/v1/streams/'+s['stream_id'])['state']=='stopped'
save('probe-intent.json',dict(camera_id=3,attempts=1))
def limits():
    resource.setrlimit(resource.RLIMIT_CPU,(5,5))
    resource.setrlimit(resource.RLIMIT_AS,(512*1024**2,512*1024**2))
try:
    p=subprocess.run(['ffprobe','-v','error','-rtsp_transport','tcp','-timeout','5000000','-threads','1',
        '-probesize','65536','-analyzeduration','1000000','-read_intervals','%+1','-select_streams','v:0',
        '-show_packets','-show_entries','packet=pts_time','-of','json',s['uri']],capture_output=True,text=True,timeout=9,preexec_fn=limits)
    pts=[float(x['pts_time']) for x in json.loads(p.stdout).get('packets',[]) if 'pts_time' in x] if p.returncode==0 else []
    result=dict(ok=len(pts)>1 and max(pts)>min(pts),packets=len(pts),elapsed_media=max(pts)-min(pts) if pts else None)
except Exception:result=dict(ok=False,reason='INPUT_UNAVAILABLE')
save('probe.json',result)
if result['ok']:save('selected-source.json',s,private=True)
print(json.dumps(result))
