from ops import *
image=json.loads((HERE/'image-6d1173df6e.json').read_text())
expected=json.loads((PRIVATE/'compose-before.json').read_text())
a=expected['services']['analytics'];a['image']=image['id']
a['environment'].update(CONTEXTRA_TRAINING_ROOT='/data/contextra/training',CONTEXTRA_TRAINING_MODEL_VERSION='8')
a['volumes'].append(dict(type='bind',source='/data/contextra/training',target='/data/contextra/training',bind={'create_host_path':False}))
actual=json.loads(cmd(compose()+['config','--format','json']))
for value in (actual,expected):
    value['services']['analytics']['volumes'].sort(key=lambda v:v['target'])
assert actual==expected,'Unexpected Compose drift'
save('compose-expected.json',actual,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']))
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,training=training()))
print('New image ready; persistent training defaults active',flush=True)
