import pathlib,subprocess,json,os,time,urllib.request,threading
from observe import Observer
os.umask(0o077);R=pathlib.Path('/evidence')
result={'stage':'model_loading','model_execution':True}
(R/'result.json').write_text(json.dumps(result))
server=subprocess.Popen(['/opt/tritonserver/bin/tritonserver','--model-repository=/models','--model-control-mode=explicit',
 '--load-model=RFDETRMedium','--exit-timeout=10','--pinned-memory-pool-byte-size=268435456',
 '--cuda-memory-pool-byte-size=0:67108864'],stdout=subprocess.DEVNULL,stderr=subprocess.DEVNULL)
try:
 end=time.monotonic()+120;ready=False
 while time.monotonic()<end and server.poll() is None:
  try:
   with urllib.request.urlopen('http://127.0.0.1:8000/v2/models/RFDETRMedium/versions/2/ready',timeout=2) as f:ready=f.status==200
   if ready:break
  except Exception:pass
  time.sleep(1)
 assert ready,'isolated readiness failed'
 result['stage']='infer_started';(R/'result.json').write_text(json.dumps(result))
 env=os.environ.copy();env.update(GST_DEBUG='GST_EVENT:5,GST_PADS:6,GST_SCHEDULING:5,nvinferserver:5',GST_DEBUG_NO_COLOR='1',OBS_ORIGIN=str(time.monotonic()))
 os.environ['OBS_ORIGIN']=env['OBS_ORIGIN']
 child=subprocess.Popen(['python3',str(R/'live.py')],env=env,stdout=subprocess.PIPE,stderr=subprocess.STDOUT,text=True)
 obs=Observer(R/'observation.json')
 def read():
  try:
   for line in child.stdout:obs.consume(line)
  finally:obs.save()
 reader=threading.Thread(target=read,daemon=True);reader.start()
 try:child.wait(90);result.update(stage='probe_finished',returncode=child.returncode)
 except subprocess.TimeoutExpired:child.kill();child.wait(5);result.update(stage='probe_timeout')
 reader.join(5);result['reader_alive']=reader.is_alive()
finally:
 server.terminate()
 try:server.wait(15)
 except subprocess.TimeoutExpired:server.kill();server.wait(5)
 result['triton_stopped']=server.poll() is not None
 (R/'result.json').write_text(json.dumps(result,indent=2))
print(json.dumps(result))

