from ops import *
import yaml, sys
phase=sys.argv[1]; assert phase in ('baseline', 'source-baseline', 'source-baseline-r2', 'candidate', 'final', 'promoted')
image=json.loads(sorted(HERE.glob('image-*.json'),key=lambda p:p.stat().st_mtime)[-1].read_text())
expected=json.loads((PRIVATE/'compose-before.json').read_text())
if phase=='promoted': expected['services']['analytics']['environment']['CONTEXTRA_SOURCE_LATEST_TRIAL']='true'
live=json.loads(cmd(compose()+['config','--format','json']))
# Only this run's image pointer may have changed since the preserved baseline.
for value in (live, expected): value['services']['analytics']['image']='IMAGE'
assert live==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)
cmd(['docker','stop','--time','20','contextra-ai-gateway-1'],timeout=30)
env_file=Path('/workspace/contextra-runtime-config/web-start-candidate-20260918/candidate.env')
lines=env_file.read_text().splitlines(); key='CONTEXTRA_SECURE_ANALYTICS_IMAGE='
assert sum(line.startswith(key) for line in lines)==1
env_file.write_text('\n'.join(key+image['id'] if line.startswith(key) else line for line in lines)+'\n')
overlay=PRIVATE/('phase-'+phase+'.yaml')
env={'CONTEXTRA_TEST_NO_CAPTURE':'false','CONTEXTRA_INPUT_TIMING_SECONDS':'0' if phase in ('final','promoted') else '900',
     'CONTEXTRA_PIPELINE_DIAGNOSTICS':'false' if phase in ('final','promoted') else 'true',
     'CONTEXTRA_COMPLETED_QUEUE_MAX_AGE_SECONDS':'1'}
env['CONTEXTRA_SOURCE_LATEST_TRIAL']='true' if phase in ('candidate','promoted') else 'false'
with overlay.open('w') as f: yaml.safe_dump({'services':{'analytics':{'environment':env}}},f)
overlay.chmod(0o600)
save('reflect-'+phase+'-intent.json',dict(image=image['id'],options=env))
cmd(['docker','stop','--signal=SIGTERM','--timeout=-1','contextra-analytics-1'],timeout=90)
assert inspect('contextra-analytics-1')['State']['ExitCode']==0
cmd(compose()+['-f',str(overlay),'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)
actual=dict(s.split('=',1) for s in inspect('contextra-analytics-1')['Config']['Env'])
assert all(actual.get(k)==v for k,v in env.items())
assert inspect('contextra-analytics-1')['Image']==image['id']
save('reflect-'+phase+'-done.json',dict(image=image,options=env,ready=True))
print(json.dumps(dict(phase=phase,image=image['tag'],ready=True)))
