"""Current-person image-plane measurements, independent of labels, T and history."""
import math

def distance(a,b):return math.hypot(a[0]-b[0],a[1]-b[1])
def joint_angle(a,b,c):
 u=(a[0]-b[0],a[1]-b[1]);v=(c[0]-b[0],c[1]-b[1]);length=math.hypot(*u)*math.hypot(*v)
 if length<1e-8:return None
 return math.degrees(math.acos(max(-1.,min(1.,(u[0]*v[0]+u[1]*v[1])/length))))

def measure(person,base,joint_score=.10):
 box=person['bbox'];w,h=box[2]-box[0],box[3]-box[1]
 result=dict(available=False,reason=None,aspect=None,torso_angle=None,torso_ratio=None,shoulder_below_hip=None,legs=[],shoulder_width_ratio=None,hip_width_ratio=None)
 if not base['eligible'] or base['torso'] is None or w<=0 or h<=0:
  result['reason']='R1_PERSON_OR_TORSO_UNAVAILABLE';return result
 diag=math.hypot(w,h);torso=base['torso'];points=[k[:2] if len(k)==3 and all(math.isfinite(v) for v in k) and k[2]>=joint_score else None for k in person['keypoints']]
 result.update(aspect=w/h,torso_angle=torso['angle'],torso_ratio=torso['length_ratio'],shoulder_below_hip=(torso['top'][1]-torso['bottom'][1])/h)
 for key,a,b in [('shoulder_width_ratio',5,6),('hip_width_ratio',11,12)]:
  if points[a] is not None and points[b] is not None:result[key]=distance(points[a],points[b])/diag
 for side,hip,knee,ankle in [('left',11,13,15),('right',12,14,16)]:
  if any(points[j] is None for j in (hip,knee,ankle)):continue
  a,b,d=points[hip],points[knee],points[ankle];length=distance(a,d)/diag
  thigh=distance(a,b)/diag;shin=distance(b,d)/diag;ang=joint_angle(a,b,d)
  if ang is None or not .04<=length<=1.15 or min(thigh,shin)<.02 or max(thigh,shin)>1.15:continue
  result['legs'].append(dict(side=side,knee_angle=ang,length_ratio=length,thigh_ratio=thigh,shin_ratio=shin,
   ankle_drop=(d[1]-a[1])/h,knee_drop=(b[1]-a[1])/h,angle=math.degrees(math.atan2(abs(d[0]-a[0]),abs(d[1]-a[1]))),joints=[hip,knee,ankle]))
 result['available']=bool(result['legs']);result['reason']=None if result['available'] else 'FULL_LEG_GEOMETRY_UNAVAILABLE'
 return result
