"""
stat_bar — a percentage bar that is proven by geometry and printed static.

The data-overlay rule (2026-09-03 motion-design port): a number on screen is
never generated and never counted up. The full-length 100% track is drawn
FIRST with its own visible outline, the fill is exactly `pct` of that track,
and the label is printed complete from its first frame. A viewer can check the
number against the bar; the bar can never contradict the label.

Usage inside an engine beat function (PIL ImageDraw):

    from lib.stat_bar import stat_bar
    stat_bar(dr, x=120, y=400, w=800, h=36, pct=0.5,
             track=(28, 28, 28), fill=(209, 239, 23), outline=(28, 28, 28),
             label="50%", font=FONT_LABEL, label_fill=(28, 28, 28))

Returns the (x0, y0, x1, y1) box of the fill so a caller can place a marker.
"""
from __future__ import annotations

from typing import Optional, Tuple

RGB = Tuple[int, int, int]


def stat_bar(
    dr,
    x: int,
    y: int,
    w: int,
    h: int,
    pct: float,
    *,
    track: RGB,
    fill: RGB,
    outline: Optional[RGB] = None,
    outline_width: int = 2,
    radius: int = 0,
    label: Optional[str] = None,
    font=None,
    label_fill: Optional[RGB] = None,
    label_gap: int = 16,
) -> Tuple[int, int, int, int]:
    """Draw a static, geometry-proven percentage bar.

    `pct` is clamped to [0, 1]. The track is always the full `w`, drawn first;
    the fill width is `round(w * pct)` so 0.5 is exactly half and 1.0 is edge
    to edge. Nothing here animates: call it every frame with the same values.
    """
    if not 0.0 <= pct <= 1.0:
        pct = min(1.0, max(0.0, pct))
    x0, y0, x1, y1 = x, y, x + w, y + h
    # 1. the 100% track, full length, visible even when the fill is short
    if radius > 0:
        dr.rounded_rectangle((x0, y0, x1, y1), radius=radius, fill=track,
                             outline=outline, width=outline_width if outline else 0)
    else:
        dr.rectangle((x0, y0, x1, y1), fill=track, outline=outline,
                     width=outline_width if outline else 0)
    # 2. the fill: exactly pct of the track, from the left edge
    fw = int(round(w * pct))
    fill_box = (x0, y0, x0 + fw, y1)
    if fw > 0:
        if radius > 0:
            dr.rounded_rectangle(fill_box, radius=radius, fill=fill)
        else:
            dr.rectangle(fill_box, fill=fill)
    # 2b. redraw the outline so the fill never paints over the track's border
    if outline:
        if radius > 0:
            dr.rounded_rectangle((x0, y0, x1, y1), radius=radius, outline=outline, width=outline_width)
        else:
            dr.rectangle((x0, y0, x1, y1), outline=outline, width=outline_width)
    # 3. the label, printed complete, just past the track's right end
    if label is not None and font is not None:
        dr.text((x1 + label_gap, y0 + h // 2), label, font=font,
                fill=label_fill or fill, anchor="lm")
    return fill_box
