"""Bounded numeric-only observation, using the existing Redis connection."""
import hashlib,json,os,signal,time
import redis

MARKER='contextra-crowd-a13-reader-r01'
stop=False
def ending(*args):
    global stop
    stop=True
signal.signal(signal.SIGTERM,ending)
c=redis.from_url(os.environ['CONTEXTRA_METADATA_REDIS_URL'],decode_responses=True,socket_timeout=3,socket_connect_timeout=3)
ns=os.environ.get('CONTEXTRA_METADATA_NAMESPACE','contextra:metadata:v1')
cursors={}
for camera in range(30,43):
    key=ns+':camera:'+hashlib.sha256(str(camera).encode()).hexdigest()+':frames'
    tail=c.xrevrange(key,count=1);cursors[key]=tail[0][0] if tail else '0-0'
print(json.dumps(dict(kind='ready',pid=os.getpid(),marker=MARKER)),flush=True)
start=time.monotonic();count=0
try:
    while not stop and time.monotonic()-start<40 and count<25000:
        for key,entries in c.xread(cursors,count=100,block=200):
            for sid,fields in entries:
                cursors[key]=sid;s=json.loads(fields['json'])
                if s.get('providerKey') not in ('pose','fire','crowd'):continue
                print(json.dumps(dict(kind='frame',camera=s['cameraId'],provider=s['providerKey'],model=s.get('providerModel'),
                    required=s.get('requiredProviders'),run=s['runId'],seq=s['frameSeq'],pts=s['ptsNs'],redis_id=sid,
                    read_wall_ms=time.time_ns()//1000000,read_mono_ns=time.monotonic_ns(),
                    regions=(s.get('crowd') or {}).get('regions'),
                    event_scenarios=[e['scenario'] for e in s.get('events',[])])),flush=True)
                count+=1
finally:
    c.close();print(json.dumps(dict(kind='finished',seconds=time.monotonic()-start,frames=count)),flush=True)
