"""POSEPATH-01: debug masks never mutate the shared raw Pose observation."""
from app.pose_config import JOINT_NAMES

EDGES = ((0,1),(0,2),(1,3),(2,4),(5,6),(5,7),(7,9),(6,8),(8,10),
         (5,11),(6,12),(11,12),(11,13),(13,15),(12,14),(14,16))


def joint_color(index):
    if index in (0,5,6,11,12):
        return '#FFD84D'
    return '#20D8EB' if JOINT_NAMES[index].startswith('left') else '#ED59CF'


def pose_summary(result):
    cfg = result.pose_config
    rows = []
    if cfg is None:
        return dict(shown=0,filtered=0,objects=[])
    for index,c in enumerate(result.commands):
        if not c.visible or c.pose is None:
            continue
        valid = [k[2]>=cfg.joint_score and 0<=k[0]<=1 and 0<=k[1]<=1 for k in c.pose.keypoints]
        count = sum(valid)
        rows.append(dict(objectRef=str(index),trackId=c.track_id,personScore=c.detection.score,
                         validJoints=count,totalJoints=17,eligible=count>=cfg.min_joints))
    return dict(shown=sum(r['eligible'] for r in rows),filtered=sum(not r['eligible'] for r in rows),objects=rows)


def draw_pose(draw,result,width,height,header):
    cfg = result.pose_config
    summary = pose_summary(result)
    if cfg is None:
        return summary
    for row in summary['objects']:
        if not row['eligible']:
            continue
        c = result.commands[int(row['objectRef'])]
        points = c.pose.keypoints
        valid = [k[2]>=cfg.joint_score and 0<=k[0]<=1 and 0<=k[1]<=1 for k in points]
        pixel = [(min(width-1,max(0,round(k[0]*width))),header+min(height-1,max(0,round(k[1]*height)))) for k in points]
        if cfg.show_edges:
            for a,b in EDGES:
                if valid[a] and valid[b]:
                    draw.line((pixel[a],pixel[b]),fill=joint_color(b),width=2)
        detail = (cfg.detail_track_id is not None and c.track_id==cfg.detail_track_id) or (
            cfg.detail_object_ref==row['objectRef'] and cfg.detail_frame_seq==result.frame.frame_seq)
        for j,((x,y),usable) in enumerate(zip(pixel,valid)):
            if not usable:
                continue
            if cfg.show_joints:
                draw.ellipse((x-3,y-3,x+3,y+3),fill=joint_color(j),outline='#181818')
            if detail and (cfg.show_joint_names or cfg.show_joint_scores):
                from app.metadata_render import text_fit
                text = JOINT_NAMES[j] if cfg.show_joint_names else ''
                if cfg.show_joint_scores: text += f' {points[j][2]:.2f}'
                text_fit(draw,(max(0,min(x+5,width-165)),max(header,min(y,header+height-18))),text,160,12)
    return summary
