import hashlib
import json
import os
import time
import urllib.request
from pathlib import Path
import yaml
import psycopg2
from psycopg2.extras import RealDictCursor

sid='camera-1fdaa47a21ac5365934a42c53f6d327f'
with urllib.request.urlopen('http://127.0.0.1:5000/api/v1/streams/'+sid+'/settings',timeout=5) as r: settings=json.load(r)
token=Path(os.environ['CONTEXTRA_CONTROL_TOKEN_FILE']).read_text().strip()
q=urllib.request.Request('http://127.0.0.1:5000/internal/secure-control/runtime-status',headers={'Authorization':'Bearer '+token})
with urllib.request.urlopen(q,timeout=5) as r: runtime=json.load(r)
stream=next(x for x in runtime['streams'] if str(x.get('cameraId'))=='24')
path=Path(os.environ.get('STREAMS_RUNTIME_PATH','/var/lib/contextra/runtime/streams_runtime.yaml'))
saved=yaml.safe_load(path.read_text())
matches=[]
def walk(value):
    if isinstance(value,dict):
        if str(value.get('stream_id'))==sid:matches.append(value)
        for child in value.values():walk(child)
    elif isinstance(value,list):
        for child in value:walk(child)
walk(saved)
assert len(matches)==1
spec=matches[0]
with psycopg2.connect(os.environ['DATABASE_URL'],connect_timeout=3,options='-c statement_timeout=2500 -c default_transaction_read_only=on') as conn:
    with conn.cursor(cursor_factory=RealDictCursor) as cur:
        cur.execute('''SELECT event_id,payload,relative_path,artifact_state,delivery_state,
            attempts,error,delivery_error,http_status,media,created_at,updated_at
            FROM contextra_event_artifacts WHERE event_id IN (%s,%s)''',
            ('7da55541-7109-4bd8-a577-419dad502542','6869fca8-a343-42f1-9ad9-994052c9eb2a'))
        events=[dict(x) for x in cur.fetchall()]
    conn.rollback()
keep=('fight','pose','tracking','analysisFpsTarget','display_categories')
print(json.dumps({'at_ms':time.time_ns()//1000000,'runtime':stream,
    'settings':{k:{n:v[n] for n in keep if n in v} if isinstance(v,dict) else v for k,v in settings.items() if k in ('configured','effective','restart_pending')},
    'saved_event_cooldowns':spec.get('event_cooldowns'),
    'default_event_cooldown':os.environ.get('CONTEXTRA_EVENT_COOLDOWN_SECONDS','10'),
    'runtime_overlay_sha256':hashlib.sha256(path.read_bytes()).hexdigest(),
    'events':events}))
