"""No Start/Stop/PATCH; credentials are piped without persistence."""
import sys,json,time,os,importlib.util
from pathlib import Path
spec=importlib.util.spec_from_file_location('ops','/tmp/codex/ltb1021/2026-09-27_pose-mixed-baseline_r01/ops.py')
ops=importlib.util.module_from_spec(spec);spec.loader.exec_module(ops)
HERE=Path(__file__).parent;os.umask(0o077)
camera=int(sys.argv[1]) if len(sys.argv)>1 else 3
seconds=float(sys.argv[2]) if len(sys.argv)>2 else 30
OUT=Path(sys.argv[3]).resolve() if len(sys.argv)>3 else HERE
assert OUT.is_relative_to(Path('/tmp/codex/ltb1021'))
OUT.mkdir(mode=0o700,parents=True,exist_ok=True)
assert not (OUT/'observation.json').exists(),'Choose a new run directory'
def status():
 rows=ops.api('/api/v1/streams')['streams']
 active=[r for r in rows if r['state']=='running']
 assert len(active)==1,'Bounded helper requires one running channel'
 r=active[0];s=ops.api('/api/v1/streams/'+r['stream_id']+'/settings')
 allowed=('revision','display_score','pose','tracking','analysisFpsTarget','fall','fight','fire','crowd','intrusion','loitering')
 def clean(v):
  if isinstance(v,dict):return {k:clean(x) for k,x in v.items() if k not in ('roi','rois','roi_name')}
  if isinstance(v,list):return [clean(x) for x in v]
  return v
 return dict(wall=time.time(),run=r['run_id'],state=r['state'],scenarios=r['scenarios'],
  settings={k:clean({f:v.get(f) for f in allowed}) for k,v in s.items() if k in ('configured','effective')},
  providers={p:{k:v.get(k) for k in ('state','child_pid','last_error','metadata_path','publisher_metrics')} for p,v in r['provider_processes'].items()})
before=status();code=(HERE/'redis_window.py').read_text()
auth=Path('/workspace/contextra-runtime-config/metadata-active/reader/reader-credentials.json')
assert not auth.is_symlink() and auth.stat().st_mode&0o077==0
raw=json.loads(ops.cmd(['docker','exec','-i','contextra-analytics-1','python3','-B','-c',code,str(camera),str(seconds)],input=auth.read_text(),timeout=seconds+15))
after=status();assert before['run']==after['run'],'Run changed during observation'
out=dict(image=ops.inspect('contextra-analytics-1')['Image'],before=before,after=after,redis=raw)
with (OUT/'observation.json').open('x') as f:json.dump(out,f,indent=2)
print(json.dumps(dict(seconds=raw['seconds'],messages=len(raw['rows']),providers=raw['info'],state=after['state'])))
