import hashlib
import json
import os
import time
import urllib.request
from pathlib import Path

import psycopg2
import yaml
from psycopg2.extras import RealDictCursor

token = Path(os.environ['CONTEXTRA_CONTROL_TOKEN_FILE']).read_text().strip()
request = urllib.request.Request('http://127.0.0.1:5000/internal/secure-control/runtime-status',
                                headers={'Authorization': 'Bearer ' + token})
with urllib.request.urlopen(request, timeout=5) as response:
    runtime = json.load(response)
stream = next(x for x in runtime['streams'] if str(x.get('cameraId')) == '24')
sid = stream['streamId']
with urllib.request.urlopen('http://127.0.0.1:5000/api/v1/streams/' + sid + '/settings', timeout=5) as response:
    settings = json.load(response)
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
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 cursor:
        cursor.execute("""SELECT event_id,payload,relative_path,artifact_state,delivery_state,
            error,delivery_error,http_status,media,created_at,updated_at
            FROM contextra_event_artifacts WHERE payload->>'cameraId'='24'
            ORDER BY created_at DESC LIMIT 3""")
        events = [dict(x) for x in cursor.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': matches[0].get('event_cooldowns'),
    'runtime_overlay_sha256': hashlib.sha256(path.read_bytes()).hexdigest(),
    'recent_events': events,
}))
