import os,glob,json,pathlib,time,threading
assert not glob.glob('/dev/nvidia*');os.umask(0o077)
os.environ['DATABASE_URL']='postgresql://u:p'+chr(64)+'localhost:1/db'
os.environ['REDIS_STREAMS_ENABLED']='false'
from stdin_guard import install
stdin_info=install()
from pyservicemaker import Pipeline,Probe,BufferOperator
from app.multi_pipeline import _pipeline_message_callback
from app.stream_lifecycle import RoleRunHandle
R=pathlib.Path('/evidence');start=float(os.environ['OBS_ORIGIN']);timeline=[];counts={'buffers':0,'eos':0}
enough=threading.Event();lock=threading.Lock()
def mark(stage):
 with lock:
  value=round(time.monotonic()-start,6);timeline.append({'stage':stage,'seconds':value})
  print('OBS '+json.dumps({'stage':stage,'s':value}),flush=True)
handle=RoleRunHandle('det',1)
delegate=_pipeline_message_callback(handle,finite=False)
def message(msg):
 if type(msg).__name__=='EOSMessage':counts['eos']+=1;mark('bus_eos')
 delegate(msg)
class Counter(BufferOperator):
 def handle_buffer(self,buffer):
  counts['buffers']+=1
  if counts['buffers']>=5:enough.set()
  return True
p=Pipeline('cpu-live-stop')
p.add('videotestsrc','source',{'is-live':True})
p.add('capsfilter','caps',{'caps':'video/x-raw,width=64,height=64,framerate=10/1'})
p.add('identity','infer-infer-0');p.add('fakesink','retrieve-appsink-2',{'sync':False})
p.link('source','caps','infer-infer-0','retrieve-appsink-2');probe=Probe('counter',Counter());p.attach('infer-infer-0',probe)
handle.bind_pipeline(p)
def worker():
 try:
  mark('start_enter');waiter=handle.start_pipeline(message);mark('start_returned')
  waiter.wait();mark('wait_returned')
 except Exception as e:mark('worker_'+type(e).__name__)
t=threading.Thread(target=worker,daemon=True);handle.bind_thread(t);t.start()
arrived=enough.wait(5)
def stop():
 mark('stop_enter');failure=handle.stop();mark('stop_returned' if failure is None else 'stop_failed')
s=threading.Thread(target=stop,daemon=True);s.start();s.join(5);t.join(5)
result=dict(live=True,arrived=arrived,counts=counts,timeline=timeline,stop_alive=s.is_alive(),wait_alive=t.is_alive(),
            failure=handle.failure.as_dict() if handle.failure else None,gpu_nodes=0,stdin=stdin_info)
(R/'cpu.json').write_text(json.dumps(result,indent=2));print(json.dumps(result))

assert arrived and counts['eos']==1 and not s.is_alive() and not t.is_alive()
