"""Highlight scene: rectangle around a target element (or union of several)."""
from __future__ import annotations

from .. import js_loader
from ..browser import resolve_locator
from . import register


def _union_box(page, selectors: list[str]) -> dict | None:
    """Compute the union bounding box of every matching selector. Skips misses."""
    # Make sure the first one is visible / on-screen before measuring.
    resolve_locator(page, selectors[0])
    boxes: list[dict] = []
    for sel in selectors:
        try:
            loc = page.locator(sel).first
            b = loc.bounding_box()
        except Exception:
            continue
        if b:
            boxes.append(b)
    if not boxes:
        return None
    x = min(b["x"] for b in boxes)
    y = min(b["y"] for b in boxes)
    right = max(b["x"] + b["width"] for b in boxes)
    bottom = max(b["y"] + b["height"] for b in boxes)
    return {"x": x, "y": y, "width": right - x, "height": bottom - y}


@register("highlight")
def scene_highlight(page, scene: dict) -> None:
    selectors = scene.get("selectors")
    if selectors:
        box = _union_box(page, list(selectors))
        if not box:
            raise RuntimeError(f"highlight: no bounding boxes for {selectors}")
    else:
        locator = resolve_locator(page, scene["selector"])
        box = locator.bounding_box()
        if not box:
            raise RuntimeError(f"highlight: no bounding box for {scene['selector']}")
    page.evaluate(
        js_loader.load("highlight"),
        {
            "box": box,
            "pad": scene.get("padding", 8),
            "color": scene.get("color", "#ff3b30"),
            "lw": scene.get("lineWidth", 4),
            "label": scene.get("label", ""),
            "drawOnMs": int(scene.get("drawOnMs", 0)),
        },
    )
    page.wait_for_timeout(scene.get("duration", 3000))
