"""Drawing primitives and visual constants for the overlay renderer."""

import cv2


def blend_overlay(frame, overlay, x, y, alpha=0.75):
    """Alpha-blend an overlay onto the frame at (x, y)."""
    oh, ow = overlay.shape[:2]
    fh, fw = frame.shape[:2]
    x1, y1 = max(x, 0), max(y, 0)
    x2, y2 = min(x + ow, fw), min(y + oh, fh)
    ox1, oy1 = x1 - x, y1 - y
    ox2, oy2 = ox1 + (x2 - x1), oy1 + (y2 - y1)
    if x2 <= x1 or y2 <= y1:
        return
    roi = frame[y1:y2, x1:x2]
    blended = cv2.addWeighted(overlay[oy1:oy2, ox1:ox2], alpha, roi, 1 - alpha, 0)
    frame[y1:y2, x1:x2] = blended


def rounded_rect(img, pt1, pt2, color, radius, thickness=-1):
    """Draw a rectangle with rounded corners."""
    x1, y1 = pt1
    x2, y2 = pt2
    r = min(radius, (x2 - x1) // 2, (y2 - y1) // 2)
    if r < 1:
        cv2.rectangle(img, pt1, pt2, color, thickness)
        return
    cv2.rectangle(img, (x1 + r, y1), (x2 - r, y2), color, thickness)
    cv2.rectangle(img, (x1, y1 + r), (x2, y2 - r), color, thickness)
    for cx, cy in [(x1 + r, y1 + r), (x2 - r, y1 + r), (x1 + r, y2 - r), (x2 - r, y2 - r)]:
        cv2.circle(img, (cx, cy), r, color, thickness, cv2.LINE_AA)


def pill(img, x, y, w, h, color, thickness=-1):
    """Draw a pill / stadium shape (rectangle with semicircle ends)."""
    r = h // 2
    cv2.rectangle(img, (x + r, y), (x + w - r, y + h), color, thickness)
    cv2.circle(img, (x + r, y + r), r, color, thickness, cv2.LINE_AA)
    cv2.circle(img, (x + w - r, y + r), r, color, thickness, cv2.LINE_AA)


SIGNAL_CHANNELS = [
    ("BLINK", "Blink", (92, 92, 255)),
    ("HEAD-NOD", "Nod", (60, 180, 255)),
    ("HEAD-SHAKE", "Shake", (220, 185, 55)),
    ("HEAD-TILT", "Tilt", (210, 130, 210)),
    ("MOUTH-MOVEMENT", "Mouth", (80, 210, 130)),
    ("EYEBROW-RAISE", "Brow Up", (90, 215, 245)),
    ("EYEBROW-FURROW", "Brow Down", (140, 130, 230)),
    ("EYE-GAZE", "Gaze", (255, 180, 80)),
    ("EYE-SQUINT", "Squint", (180, 140, 255)),
]

TIER_SHORT = {
    "BLINK": "B",
    "HEAD-NOD": "N",
    "HEAD-SHAKE": "S",
    "HEAD-TILT": "T",
    "MOUTH-MOVEMENT": "M",
    "EYEBROW-RAISE": "Br",
    "EYEBROW-FURROW": "Bf",
    "EYE-GAZE": "G",
    "EYE-SQUINT": "Sq",
}
