from ops import *
expected=json.loads((PRIVATE/'compose-before.json').read_text())
expected['services']['analytics']['environment'].update(CONTEXTRA_PROVIDER_FRESHNESS_ENABLED='false',CONTEXTRA_PROVIDER_LINEAR_TRIAL='true')
assert json.loads(cmd(compose()+['config','--format','json']))==expected
assert all(r['state']=='stopped' and not r.get('child_pid') and not r.get('cleanup_pending') for r in api('/api/v1/streams')['streams'])
save('reflection-intent.json',dict(image=inspect('contextra-analytics-1')['Image'],linear=True,freshness=False))
cmd(['docker','stop','--time','20','contextra-ai-gateway-1'],timeout=30)
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)
env=dict(x.split('=',1) for x in inspect('contextra-analytics-1')['Config']['Env'])
assert env['CONTEXTRA_PROVIDER_LINEAR_TRIAL']=='true' and env['CONTEXTRA_PROVIDER_FRESHNESS_ENABLED']=='false'
save('reflection-done.json',dict(image=inspect('contextra-analytics-1')['Image'],ready=True,linear=True,freshness=False))
print('ready; persistent/runtime B and OFF match')
