from ops import *
import sys
trial=len(sys.argv)>1 and sys.argv[1]=='trial'
images=list(HERE.glob('image-*.json'));assert len(images)==1
image=json.loads(images[0].read_text())
expected=json.loads((PRIVATE/'compose-before.json').read_text())
expected['services']['analytics']['image']=image['id']
assert json.loads(cmd(compose()+['config','--format','json']))==expected
overlay=PRIVATE/'queue2.yaml'
if trial and not overlay.exists():
    overlay.write_text('services:\n  analytics:\n    environment:\n      CONTEXTRA_COMPLETED_QUEUE_MAX_AGE_SECONDS: "2"\n')
    overlay.chmod(0o600)
command=compose()+(['-f',str(overlay)] if trial else [])
assert not inspect('contextra-ai-gateway-1')['State']['Running']
rows=api('/api/v1/streams')['streams']
assert all(not r.get('child_pid') and not r.get('cleanup_pending') and not any(v.get('child_pid') for v in r.get('provider_processes',{}).values()) for r in rows)
save('reflection-'+('trial' if trial else 'final')+'-intent.json',dict(image=image['id'],queue_seconds=2 if trial else 1))
cmd(['docker','stop','--signal=SIGTERM','--timeout=-1','contextra-analytics-1'],timeout=90)
assert inspect('contextra-analytics-1')['State']['ExitCode']==0
cmd(command+['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']
env=dict(x.split('=',1) for x in inspect('contextra-analytics-1')['Config']['Env'])
assert float(env.get('CONTEXTRA_COMPLETED_QUEUE_MAX_AGE_SECONDS','1'))==(2 if trial else 1)
save('reflection-'+('trial' if trial else 'final')+'-done.json',dict(image=image['id'],queue_seconds=2 if trial else 1,ready=True))
if not trial:save('compose-expected.json',expected,private=True)
print('Ready; queue seconds='+str(2 if trial else 1),flush=True)
