"""Read-only, bounded readiness/config/ledger fingerprints; no payload output."""
import hashlib
import json
import os
from pathlib import Path
import time
import urllib.request
import urllib.error

token=Path(os.environ['CONTEXTRA_CONTROL_TOKEN_FILE']).read_text().strip()

def get(url,auth=False):
    req=urllib.request.Request(url,headers={'Authorization':'Bearer '+token} if auth else {})
    try:
        with urllib.request.urlopen(req,timeout=8) as response:
            raw=response.read(1024*1024)
            try:value=json.loads(raw)
            except ValueError:value=None
            return {'code':response.status,'body':value}
    except urllib.error.HTTPError as e:return {'code':e.code}
    except Exception as e:return {'error':type(e).__name__}

out={'wall_time':time.time(),'ready':get('http://127.0.0.1:5000/ready'),
     'runtime':get('http://127.0.0.1:5000/internal/secure-control/runtime-status',True),
     'unauthorized':get('http://127.0.0.1:5000/internal/secure-control/runtime-status')}
out['models']={name:get('http://127.0.0.1:8000/v2/models/'+name+'/ready') for name in (
    'RFDETRMedium','RFDETRKeypointPreview','RFDETRFireSmoke','Awiros_person_and_head_detection')}
out['config_sha256']={}
for key,default in (('STREAMS_CONFIG_PATH','/etc/contextra/streams.yaml'),
                    ('STREAMS_RUNTIME_PATH','/var/lib/contextra/runtime/streams_runtime.yaml')):
    p=Path(os.environ.get(key,default))
    out['config_sha256'][key]=hashlib.sha256(p.read_bytes()).hexdigest() if p.exists() else None
import psycopg2
conn=psycopg2.connect(os.environ['DATABASE_URL'],connect_timeout=5,
                     options='-c statement_timeout=8000 -c lock_timeout=1000')
conn.set_session(readonly=True)
cutoff=float(os.environ.get('HOTFIX_LEDGER_CUTOFF',time.time()))
with conn.cursor() as cur:
    cur.execute("SELECT row_to_json(t)::text FROM contextra_event_artifacts t WHERE delivery_state='BLOCKED_TIME' AND created_at<=%s ORDER BY event_id",(cutoff,))
    digest=hashlib.sha256();count=0;size=0
    for row in cur:
        raw=row[0].encode();size+=len(raw);count+=1
        assert size<128*1024**2
        digest.update(raw+b'\n')
    out['blocked_time']={'cutoff':cutoff,'rows':count,'sha256':digest.hexdigest(),'bytes':size}
conn.rollback();conn.close()
print(json.dumps(out))
