"""Pixel-reduction helpers shared across single-pixel LED clients.

Single-pixel devices (Yeelight, WiZ, LIFX, Govee, Nanoleaf, BLE bulbs)
all need to collapse an N-pixel strip down to one RGB triple before
sending it on the wire. This module is the single home for that reduction
so the next single-pixel driver can drop the local copy.

Hue is the exception — its Entertainment API addresses up to seven
zones individually, so it doesn't reduce.
"""

from __future__ import annotations

from typing import List, Tuple, Union

import numpy as np


def average_color(
    pixels: Union[List[Tuple[int, int, int]], np.ndarray],
) -> Tuple[int, int, int]:
    """Reduce an N-pixel strip to one average RGB triple.

    Accepts either a list of ``(r, g, b)`` tuples or an ``(N, 3)`` uint8
    numpy array. Empty inputs return ``(0, 0, 0)`` rather than raising so
    callers can pass through a degenerate frame without branching.
    """
    if isinstance(pixels, np.ndarray):
        if pixels.size == 0:
            return (0, 0, 0)
        arr = pixels.reshape(-1, 3) if pixels.ndim > 1 else pixels[:3].reshape(1, 3)
        mean = arr.mean(axis=0)
        return int(mean[0]), int(mean[1]), int(mean[2])
    if not pixels:
        return (0, 0, 0)
    total_r = total_g = total_b = 0
    for r, g, b in pixels:
        total_r += r
        total_g += g
        total_b += b
    n = len(pixels)
    return total_r // n, total_g // n, total_b // n
