from ops import *
import sys
digest=sys.argv[1]
assert shutil.disk_usage('/').free>15*1024**3
cmd(['docker','stop','--timeout','20','contextra-ai-gateway-1'])
rows=api('/api/v1/streams')['streams']
for row in rows:
    if row['state']!='stopped':request('/api/v1/streams/'+row['stream_id']+'/stop',{})
deadline=time.monotonic()+90
while True:
    rows=api('/api/v1/streams')['streams'];a=api('/api/v1/metadata/status')['artifacts']
    if all(r['state']=='stopped' and not r.get('child_pid') and not r.get('cleanup_pending') for r in rows) and not a.get('active') and not a.get('rendering'):break
    if time.monotonic()>deadline:raise RuntimeError('DRAIN_FAILED')
    time.sleep(1)
image=json.loads((HERE/('image-'+digest+'.json')).read_text())['id']
expected=json.loads((PRIVATE/'compose-before.json').read_text());expected['services']['analytics']['image']=image
assert json.loads(cmd(compose()+['config','--format','json']))==expected
save('reflection-'+digest+'-intent.json',dict(image=image,stopped=len(rows)))
cmd(['docker','stop','--signal=SIGTERM','--timeout=-1','contextra-analytics-1'],timeout=90)
cmd(compose()+['up','-d','--no-deps','--no-build','--pull','never','analytics'],timeout=150)
deadline=time.monotonic()+120
while True:
    try:api('/ready');break
    except Exception:
        if time.monotonic()>deadline:raise RuntimeError('READY_FAILED')
        time.sleep(2)
assert inspect('contextra-analytics-1')['Image']==image
save('reflection-'+digest+'-done.json',dict(image=image,ready=True))
print(json.dumps(dict(image=image,ready=True)),flush=True)
