from ops import *
import sys,yaml
mode=sys.argv[1];assert mode in ('off','final')
image=json.loads((HERE/'image-73c04f9c8b.json').read_text())['id']
override=PRIVATE/('pose-'+mode+'.compose.yaml')
override.write_text(yaml.safe_dump({'services':{'analytics':{'environment':{
 'CONTEXTRA_PROVIDER_FRESHNESS_ENABLED':'false' if mode=='off' else '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',{}).values()) for r in rows)
deadline=time.monotonic()+60
while True:
 a=api('/api/v1/metadata/status')['artifacts']
 if not a.get('active') and not a.get('rendering'):break
 if time.monotonic()>deadline:raise RuntimeError('ARTIFACT_DRAIN')
 time.sleep(1)
full=compose()+(['-f',str(override)] if mode=='off' else [])
expected=json.loads((PRIVATE/'compose-before.json').read_text());expected['services']['analytics']['image']=image
expected['services']['analytics']['environment']['CONTEXTRA_PROVIDER_FRESHNESS_ENABLED']='false' if mode=='off' else '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)
