from ops import *
image=json.loads((HERE/'image.json').read_text())
before=json.loads((PRIVATE/'compose-before.json').read_text())
expected=json.loads(json.dumps(before));expected['services']['analytics']['image']=image['id']
assert json.loads(cmd(compose()+['config','--format','json']))==expected
rows=api('/api/v1/streams')['streams']
assert all(r['state']=='stopped' and not r.get('child_pid') and not r.get('cleanup_pending') for r in rows)
assert not inspect('contextra-ai-gateway-1')['State']['Running']
save('reflect-intent.json',image)
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('READINESS_FAILED')
        time.sleep(2)
assert inspect('contextra-analytics-1')['Image']==image['id']
for p,h in json.loads((HERE/'build-intent.json').read_text())['hashes'].items():
    assert cmd(['docker','exec','contextra-analytics-1','sha256sum','/opt/contextra/'+p]).split()[0]==h
save('reflected.json',dict(image=image,ready=True))
print(json.dumps(dict(ready=True,image=image['tag'])))
