import pathlib,subprocess,json,configparser,os,time,urllib.request
os.umask(0o077);R=pathlib.Path('/evidence');configs=list(pathlib.Path('/configs').glob('*.preprocess'));assert len(configs)==1
c=configparser.ConfigParser();c.read(configs[0]);uid=int(c['property']['unique-id'])
cmd=['g++','-std=c++17',str(R/'probe.cpp'),'-o',str(R/'probe'),'-I/opt/nvidia/deepstream/deepstream/sources/includes',
 '-I/sdk-preprocess/include','-I/usr/local/cuda/include','-L/opt/nvidia/deepstream/deepstream/lib','-lnvdsgst_meta','-lnvds_meta']
cmd+=subprocess.check_output(['pkg-config','--cflags','--libs','gstreamer-1.0'],text=True).split()
with (R/'compile.log').open('w') as log:r=subprocess.run(cmd,stdout=log,stderr=subprocess.STDOUT,timeout=30)
assert r.returncode==0,'compile failed'
result={'stage':'model_loading','model_execution':True};(R/'result.json').write_text(json.dumps(result))
with (R/'triton.log').open('w') as log:
 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=log,stderr=subprocess.STDOUT)
 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 model readiness failed'
  result['stage']='infer_started';(R/'result.json').write_text(json.dumps(result))
  with (R/'probe.log').open('w') as out:
   try:
    r=subprocess.run([str(R/'probe'),str(configs[0]),str(uid),str(configs[0])[:-11]],stdout=out,stderr=subprocess.STDOUT,timeout=45)
    result.update(stage='probe_finished',returncode=r.returncode)
   except subprocess.TimeoutExpired:result.update(stage='probe_timeout')
 finally:
  server.terminate()
  try:server.wait(15)
  except subprocess.TimeoutExpired:server.kill();server.wait(5)
  result['triton_stopped']=True;(R/'result.json').write_text(json.dumps(result,indent=2))
print(json.dumps(result))
