"""Read-only production snapshot with an explicit field allowlist."""
import datetime
import hashlib
import json
import pathlib
import urllib.request
import yaml

def get(endpoint):
    with urllib.request.urlopen('http://127.0.0.1:5000'+endpoint,timeout=15) as r:
        return json.load(r)

config = pathlib.Path('/var/lib/contextra/runtime/streams_runtime.yaml').read_bytes()
rows = yaml.safe_load(config)['added']
rows = list(rows.values()) if isinstance(rows,dict) else rows
spec = next(x for x in rows if str(x.get('camera_id'))=='24')
streams = get('/api/v1/streams?detail=true')['streams']
identity = {}
for s in streams:
    identity[s['stream_id']] = {k:s.get(k) for k in ('state','run_id','run_generation','child_pid','last_error','cleanup_pending')}
    identity[s['stream_id']]['provider_responses'] = {k:v.get('responses') for k,v in s.get('metadata_path',{}).get('providers',{}).items()}
pose = pathlib.Path('/opt/contextra/models/triton/RFDETRKeypointPreview')
result = dict(timestamp_utc=datetime.datetime.now(datetime.timezone.utc).isoformat(),
    health=get('/health'),streams=identity,config_sha256=hashlib.sha256(config).hexdigest(),
    camera24={k:spec.get(k) for k in ('camera_id','source_id','stream_id','analysis_fps_target','inference_profile','pose','tracking','fight','visualization')},
    pose_engine_sha256=hashlib.sha256((pose/'8/model.plan').read_bytes()).hexdigest(),
    pose_config_sha256=hashlib.sha256((pose/'config.pbtxt').read_bytes()).hexdigest(),
    pose_config=(pose/'config.pbtxt').read_text())
print(json.dumps(result))
