"""Descriptive feature summaries only, before locking one candidate."""
import sys,json
from collections import defaultdict
from pathlib import Path
sys.path.insert(0,'/evidence/2026-11-01_contextra-fall-spatial-28clips_r01/helpers')
from common import OUT,read,save
import numpy as np
groups=defaultdict(lambda:defaultdict(list));samples={}
for clip in read(OUT/'specs.json'):
 for line in (OUT/'work'/clip/'features.jsonl').open():
  row=json.loads(line)
  if not row['displayed']:continue
  ref=row['annotation']['reference']
  if ref=='positive_reference':keys=[clip]
  elif ref=='negative_reference':keys=[clip,'SELF_L02_ALL' if clip=='SELF_L02' else 'SELF_CXX_ALL']
  else:continue
  for p,x in zip(row['people'],row['extra']):
   if not x['available']:continue
   values={k:x[k] for k in ('aspect','torso_angle','torso_ratio','shoulder_below_hip','shoulder_width_ratio','hip_width_ratio')}
   values.update(knee_min=min(l['knee_angle'] for l in x['legs']),knee_max=max(l['knee_angle'] for l in x['legs']),
    leg_max=max(l['length_ratio'] for l in x['legs']),ankle_drop_max=max(l['ankle_drop'] for l in x['legs']),
    ankle_drop_min=min(l['ankle_drop'] for l in x['legs']),knee_drop_min=min(l['knee_drop'] for l in x['legs']))
   for key in keys:
    for field,v in values.items():
     if v is not None:groups[key][field].append(v)
   if clip not in samples and ref=='positive_reference':samples[clip]=dict(frame=row['source_frame'],features=x)
summary={k:{field:dict(n=len(v),p05=float(np.quantile(v,.05)),p50=float(np.quantile(v,.5)),p95=float(np.quantile(v,.95)),min=min(v),max=max(v)) for field,v in fields.items()} for k,fields in groups.items()}
save(OUT/'reports/feature_profiles.json',summary);save(OUT/'reports/feature_examples.json',samples)
for key in ('11_KISA_fall_C00_001_0018','12_KISA_fall_C00_010_0004','15_KISA_fall_C00_096_0008','SELF_CXX_ALL','SELF_L02_ALL'):
 print(key,json.dumps(summary.get(key,{})),flush=True)
