from ops import *
import resource,yaml

assert not (HERE/'probe-intent.json').exists(),'No repeat probes'
rows={r['stream_id']:r for r in api('/api/v1/streams')['streams']}
specs=yaml.safe_load(Path('/data/contextra/runtime-state/streams_runtime.yaml').read_text())['added']
eligible=[s for s in specs if str(s.get('source_id','')).isdigit() and s.get('server_id')
          and s.get('source_type')=='rtsp' and rows.get(s['stream_id'],{}).get('state')=='stopped'
          and not rows[s['stream_id']].get('child_pid')]
eligible.sort(key=lambda s:(str(s['source_id'])!='3',int(s['source_id'])))
save('probe-intent.json',dict(max_attempts=3,priority_camera=3))
results=[]
def limits():
    resource.setrlimit(resource.RLIMIT_CPU,(5,5))
    resource.setrlimit(resource.RLIMIT_AS,(512*1024**2,512*1024**2))
for s in eligible[:3]:
    attempt=dict(camera_id=int(s['source_id']),stream_id=s['stream_id'])
    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)
        packets=json.loads(p.stdout).get('packets',[]) if p.returncode==0 else []
        pts=[float(r['pts_time']) for r in packets if 'pts_time'in r]
        attempt.update(ok=p.returncode==0 and len(pts)>=2 and max(pts)>min(pts),
                       packets=len(packets),pts_count=len(pts),elapsed_media=max(pts)-min(pts) if pts else None,
                       error=None if p.returncode==0 else 'RTSP_PROBE_FAILED')
    except subprocess.TimeoutExpired:attempt.update(ok=False,error='TIMEOUT')
    except Exception:attempt.update(ok=False,error='PROBE_UNAVAILABLE')
    results.append(attempt);save('probe-'+str(len(results))+'.json',attempt)
    print(json.dumps(attempt),flush=True)
    if attempt['ok']:
        save('selected-source.json',s,private=True)
        break
save('probes.json',dict(attempts=results,selected=results[-1]['camera_id'] if results and results[-1]['ok'] else None))
