from ops import *
import sys,yaml
phase=sys.argv[1];assert phase in ('trial','trial-compact','final')
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())
live=json.loads(cmd(compose()+['config','--format','json']))
for c in (expected,live):c['services']['analytics']['image']='IMAGE'
assert expected==live
assert not inspect('contextra-ai-gateway-1')['State']['Running']
rows=api('/api/v1/streams')['streams']
assert all(r['state'] in (('stopped','error') if phase=='final' else ('stopped',)) and
    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)
if phase=='final':
    save('pre-final-channel-errors.json',[{k:r.get(k) for k in ('stream_id','state','last_error','cleanup_error','provider_processes')} for r in rows if r['state']=='error'])
envfile=Path('/workspace/contextra-runtime-config/web-start-candidate-20260918/candidate.env')
lines=envfile.read_text().splitlines();key='CONTEXTRA_SECURE_ANALYTICS_IMAGE='
assert sum(l.startswith(key) for l in lines)==1
envfile.write_text('\n'.join(key+image['id'] if l.startswith(key) else l for l in lines)+'\n')
flags=dict(CONTEXTRA_TEST_NO_CAPTURE='true' if phase!='final' else 'false',
 CONTEXTRA_INPUT_TIMING_SECONDS='2400' if phase!='final' else '0',
 CONTEXTRA_PIPELINE_DIAGNOSTICS='true' if phase!='final' else 'false',
 CONTEXTRA_INPUT_TIMELINE_LIMIT='2' if phase=='trial-compact' else '8',
 CONTEXTRA_SOURCE_LATEST_TRIAL='true',CONTEXTRA_COMPLETED_QUEUE_MAX_AGE_SECONDS='1')
overlay=PRIVATE/('phase-'+phase+'.yaml')
with overlay.open('x') as f:yaml.safe_dump({'services':{'analytics':{'environment':flags}}},f)
overlay.chmod(0o600);save('reflect-'+phase+'-intent.json',dict(image=image,flags=flags))
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)
end=time.monotonic()+120
while True:
    try:api('/ready');break
    except Exception:
        if time.monotonic()>end:raise RuntimeError('READY_TIMEOUT')
        time.sleep(2)
env=dict(v.split('=',1) for v in inspect('contextra-analytics-1')['Config']['Env'])
assert all(env.get(k)==v for k,v in flags.items())
assert inspect('contextra-analytics-1')['Image']==image['id']
save('reflect-'+phase+'-done.json',dict(image=image,flags=flags,ready=True))
print(json.dumps(dict(phase=phase,image=image['tag'],ready=True)))
