import json,os,pathlib,urllib.request
from preflight import R,g
os.umask(0o077)
plan=json.loads((R/'plan.json').read_text());run=json.loads((R/'run.json').read_text())
assert run['stage']=='completed' and run['rollback']=='applied'
c=g.inspect();assert c['State']['Health']['Status']=='healthy' and c['Image']==plan['analytics']['Image']
assert c['HostConfig']['RestartPolicy']==plan['analytics']['HostConfig']['RestartPolicy']
env=g.load_env_file(str(g.ENV));overlay=pathlib.Path(env['CONTEXTRA_RUNTIME_STATE_ROOT'])/'streams_runtime.yaml'
assert g.sha(overlay)==plan['overlay_hash'] and g.sha(g.ENV)==plan['env_hash']
assert g.sha(g.ENV.parent/'metadata-active/compose.yaml')==plan['active_hash']
assert g.sha(g.CFG)==plan['config_hash'] and g.sha(g.CFG.parent/'2/model.plan')==plan['plan_hash']
assert g.others()==plan['other_containers']
opener=urllib.request.build_opener(urllib.request.ProxyHandler({}))
with opener.open('http://127.0.0.1:'+env['FASTAPI_HOST_PORT']+'/api/v1/streams',timeout=3) as f:
    states=json.load(f)['streams']
assert len(states)==1 and states[0]['state']=='stopped'
spec=g.yaml.safe_load(overlay.read_text())['added'][0]
assert spec['visualization']['score_threshold']==.25
assert not (R/'visual/capture.enabled').exists()
log=(R/'runtime.private.log').read_text()
secrets=json.loads((g.ENV.parent/'metadata-active/secrets.json').read_text())
assert all(value not in log for value in secrets.values())
out=dict(analytics='healthy',stream='stopped',image=c['Image'],display_score=.25,
    gpu_mib=g.gpu(),model_auth_non_targets='preserved',restart='restored',new_capture=False,
    loader_error_count=log.count('libnvds_service_maker.so: cannot open shared object file'),
    plugin_init_count=log.count('Plugin contextra_rtp_time initialized'),
    actual_rtp='WAIT',normal_sdk_cleanup='unverified',new_image_active=False,
    previous_anchor_diagnostics='RETAIN restored previous container; remove on next approved recreate')
(R/'final.json').write_text(json.dumps(out,indent=2));print(json.dumps(out))
