"""Bounded read-only camera24 observation; never starts a stream or sends an event."""
import hashlib
import json
import os
import time
import urllib.request
import psycopg2
import redis

sid='camera-1fdaa47a21ac5365934a42c53f6d327f'
def get(path):
    with urllib.request.urlopen('http://127.0.0.1:5000'+path,timeout=5) as r:
        return json.load(r)
def status():
    s=get('/api/v1/streams/'+sid)
    m=s.get('metadata_path') or {}
    return dict(state=s.get('state'),run_id=s.get('run_id'),
                notification=m.get('fight_notification'),processed=m.get('processed'))
before=status()
assert before['state']=='running', 'CAMERA24_NOT_RUNNING_NO_START'
settings=get('/api/v1/streams/'+sid+'/settings')
settings={k:v.get('fight') for k,v in settings.items() if k in ('configured','effective') and isinstance(v,dict)}
c=redis.from_url(os.environ['CONTEXTRA_METADATA_REDIS_URL'],decode_responses=True,
    socket_connect_timeout=1,socket_timeout=2,max_connections=1)
key=os.environ.get('CONTEXTRA_METADATA_NAMESPACE','contextra:metadata:v1')+':camera:'+hashlib.sha256(b'24').hexdigest()+':frames'
tail=c.xrevrange(key,count=1);cursor=tail[0][0] if tail else '0-0'
start=time.monotonic(); started=time.time(); frames=[]; samples=[]; next_sample=start
while time.monotonic()-start<60:
    for _,entries in c.xread({key:cursor},count=50,block=250):
        for ident,fields in entries:
            cursor=ident
            d=json.loads(fields['json'])
            frames.append({k:d[k] for k in ('frameSeq','ptsNs','runId','objects','scenarioResults') if k in d})
            assert len(frames)<=1200
    if time.monotonic()>=next_sample:
        s=status();s['elapsed']=time.monotonic()-start;samples.append(s)
        next_sample=time.monotonic()+.25
c.close()
with psycopg2.connect(os.environ['DATABASE_URL'],connect_timeout=3,
    options='-c statement_timeout=2500 -c default_transaction_read_only=on') as db:
    with db.cursor() as q:
        q.execute("SELECT event_id,payload->>'frameSeq',artifact_state,delivery_state,http_status FROM contextra_event_artifacts WHERE created_at >= %s AND payload->>'cameraId'='24' ORDER BY created_at LIMIT 30",(started,))
        events=q.fetchall()
    db.rollback()
print(json.dumps(dict(started=started,duration=time.monotonic()-start,before=before,
    after=status(),settings=settings,samples=samples,frames=frames,events=events)))
