from ops import *
import sys,yaml
mode=sys.argv[1];assert mode in ('b','b2','final')
image=json.loads((HERE/'image-7d7a97e883.json').read_text())['id']
override=PRIVATE/'linear-trial.compose.yaml'
if mode!='final':
    override.write_text(yaml.safe_dump({'services':{'analytics':{'environment':{
        'CONTEXTRA_PROVIDER_FRESHNESS_ENABLED':'false','CONTEXTRA_PROVIDER_LINEAR_TRIAL':'true'}}}}))
    override.chmod(0o600)
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
           all(not p.get('child_pid') for p in (r.get('provider_processes') or {}).values()) for r in rows)
full=compose()+(['-f',str(override)] if mode!='final' else [])
expected=json.loads((PRIVATE/'compose-before.json').read_text());expected['services']['analytics']['image']=image
if mode!='final':expected['services']['analytics']['environment'].update({
    'CONTEXTRA_PROVIDER_FRESHNESS_ENABLED':'false','CONTEXTRA_PROVIDER_LINEAR_TRIAL':'true'})
assert json.loads(cmd(full+['config','--format','json']))==expected
save('reflection-'+mode+'-intent.json',dict(image=image,mode=mode))
cmd(['docker','stop','--signal=SIGTERM','--timeout=-1','contextra-analytics-1'],timeout=90)
assert inspect('contextra-analytics-1')['State']['ExitCode']==0
cmd(full+['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
save('reflection-'+mode+'-done.json',dict(image=image,mode=mode,ready=True))
print(json.dumps(dict(image=image,mode=mode,ready=True)),flush=True)
