from ops import *
cmd(['docker','stop','--time','20','contextra-ai-gateway-1'],timeout=30)
active=[r for r in api('/api/v1/streams')['streams'] if r['state']!='stopped']
for r in active:request('/api/v1/streams/'+r['stream_id']+'/stop',{},timeout=30)
deadline=time.monotonic()+100
while True:
    rows=api('/api/v1/streams')['streams']
    if all(r['state']=='stopped' and not r.get('child_pid') and not r.get('cleanup_pending') and
        not any(v.get('child_pid') for v in r.get('provider_processes',{}).values()) for r in rows):break
    if time.monotonic()>deadline:raise RuntimeError('STOP_REAP_BOUND')
    time.sleep(1)
save('initial-stop.json',dict(stopped=len(rows),previously_active=len(active)))
print('all channels stopped/reaped; Gateway stopped')
