from ops import *
import sys
suffix='-final' if '--final' in sys.argv else ''
assert not inspect('contextra-ai-gateway-1')['State']['Running']
deadline=time.monotonic()+90
while True:
    rows=api('/api/v1/streams')['streams'];a=api('/api/v1/metadata/status')['artifacts']
    assert all(r['state']=='stopped' and not r.get('child_pid') and not r.get('cleanup_pending') for r in rows)
    if not a.get('active') and not a.get('rendering'):break
    if time.monotonic()>deadline:raise RuntimeError('ARTIFACT_DRAIN_FAILED')
    time.sleep(1)
image=json.loads((HERE/('image'+suffix+'.json')).read_text())['id']
expected=json.loads((PRIVATE/'compose-before.json').read_text());actual=json.loads(cmd(compose()+['config','--format','json']))
expected['services']['analytics']['image']=image
assert actual==expected
save('reflection'+suffix+'-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
rows=api('/api/v1/streams')['streams'];assert all(r['state']=='stopped' for r in rows)
save('reflection'+suffix+'-done.json',dict(image=image,ready=True,channels=len(rows)))
print(json.dumps(dict(image=image,ready=True,channels=len(rows))),flush=True)
