from __future__ import annotations
from PIL import Image
import numpy as np
from .common import to_rgb


BLACK_TAIL_MAX = 0        # 0..4 -> "shadow"
WHITE_TAIL_START = 255    # 251..255 -> "highlight"


def compute_tone_metrics_from_pil(pil: Image.Image) -> tuple[float, float, float]:
    g = np.asarray(to_rgb(pil).convert("L"), dtype=np.uint8)
    vals = g.ravel()
    if vals.size == 0:
        return (0.0, 0.0, 0.0)

    hist = np.bincount(vals, minlength=256)
    total = int(hist.sum())

    black = int(hist[: BLACK_TAIL_MAX + 1].sum())
    white = int(hist[WHITE_TAIL_START :].sum())
    shadow_clip_pct = 100.0 * black / total
    highlight_clip_pct = 100.0 * white / total

    csum = np.cumsum(hist)
    p1_idx  = int(np.searchsorted(csum, 0.01 * total, side="left"))
    p99_idx = int(np.searchsorted(csum, 0.99 * total, side="left"))
    contrast_p1p99_pct = max(0.0, 100.0 * (p99_idx - p1_idx) / 255.0)
    return (round(shadow_clip_pct, 2), round(highlight_clip_pct, 2), round(contrast_p1p99_pct, 1))