from ops import *
image=json.loads((HERE/'image-65294c6b51.json').read_text())
models=json.loads((HERE/'models-prepared.json').read_text())
expected=json.loads((PRIVATE/'compose-before.json').read_text())
a=expected['services']['analytics'];a['image']=image['id']
a['environment'].update(CONTEXTRA_METADATA_STREAM_LENGTH='300',CONTEXTRA_EVENT_COOLDOWN_SECONDS='10')
for volume in a['volumes']:
    model=Path(volume['target']).name
    if model in models:volume['source']=models[model]['deployment']
assert json.loads(cmd(compose()+['config','--format','json']))==expected
save('compose-expected.json',expected,private=True)
assert not inspect('contextra-ai-gateway-1')['State']['Running']
assert all(r['state']=='stopped' and not r.get('cleanup_pending') for r in api('/api/v1/streams')['streams'])
save('reflection-intent.json',dict(image=image['id'],models=list(models)))
cmd(['docker','stop','--signal=SIGTERM','--timeout=-1','contextra-analytics-1'],timeout=90)
assert inspect('contextra-analytics-1')['State']['ExitCode']==0
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_TIMEOUT')
        time.sleep(2)
assert inspect('contextra-analytics-1')['Image']==image['id']
save('reflection-done.json',dict(image=image['id'],ready=True))
print('New image and four batch8 models reflected; ready',flush=True)
