"""Arrow scene: curved arrow from one anchor (selector/coords) to another."""
from __future__ import annotations

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


def _resolve_anchor(page, anchor: dict) -> tuple[float, float]:
    """Anchor is either {x, y} or {selector, side}. Returns page-fixed (x, y)."""
    if anchor is None:
        raise RuntimeError("arrow: missing anchor (need from/to)")
    if "x" in anchor and "y" in anchor:
        return float(anchor["x"]), float(anchor["y"])
    sel = anchor.get("selector")
    if not sel:
        raise RuntimeError("arrow: anchor needs either {x,y} or {selector}")
    loc = resolve_locator(page, sel)
    box = loc.bounding_box()
    if not box:
        raise RuntimeError(f"arrow: no bounding box for {sel}")
    side = anchor.get("side", "center")
    cx = box["x"] + box["width"] / 2
    cy = box["y"] + box["height"] / 2
    if side == "left":
        return box["x"], cy
    if side == "right":
        return box["x"] + box["width"], cy
    if side == "top":
        return cx, box["y"]
    if side == "bottom":
        return cx, box["y"] + box["height"]
    return cx, cy


@register("arrow")
def scene_arrow(page, scene: dict) -> None:
    fx, fy = _resolve_anchor(page, scene.get("from") or {})
    tx, ty = _resolve_anchor(page, scene.get("to") or {})
    page.evaluate(
        js_loader.load("arrow"),
        {
            "from": {"x": fx, "y": fy},
            "to": {"x": tx, "y": ty},
            "color": scene.get("color", "#ff3b30"),
            "lineWidth": scene.get("lineWidth", 4),
            "label": scene.get("label", ""),
        },
    )
    page.wait_for_timeout(scene.get("duration", 3000))
