"""Rule 4: rewrite every SVG ``<use>`` reference to the local theme sprite.

Matches two source patterns:
- Fragment-only: ``xlink:href="#svg-icon-foo"`` (pages that include the sprite inline).
- Absolute path: ``xlink:href="/static/sprites/global.svg#arrow-down"`` (reference
  pages, landing pages, etc. — the source CMS serves the sprite at this path,
  which does NOT exist on this project's dev/prod hosts).

Both forms are rewritten to point at
``/themes/custom/kaindl_theme/images/icons.svg#<icon-id>``. The icon id is
recorded in ``ctx.icon_ids`` so the driver can emit ``icon_inventory.json``
for the user to port into the theme sprite. Missing icons render a neutral
fallback rather than a broken image.

Also normalizes every ``<svg>`` without an accessible name to
``aria-hidden="true"`` + ``focusable="false"``.
"""

from __future__ import annotations

import re

from bs4 import BeautifulSoup, Tag

from . import TransformContext


LOCAL_SPRITE = "/themes/custom/kaindl_theme/sprites/global.svg"

# Fragment-only ref: #svg-icon-<id>.
_HASH_REF = re.compile(r"^#(svg-icon-[\w-]+)$")

# Absolute remote sprite ref: /static/sprites/<file>.svg#<id>.
_SPRITE_PATH_REF = re.compile(r"^/static/sprites/[^#]*\.svg#([\w-]+)$")


def _resolve_icon_id(href: str) -> str | None:
    """Return the bare icon id if ``href`` matches one of the known forms."""
    stripped = href.strip()
    m = _HASH_REF.match(stripped)
    if m:
        return m.group(1)
    m = _SPRITE_PATH_REF.match(stripped)
    if m:
        return m.group(1)
    return None


def transform(soup: BeautifulSoup, ctx: TransformContext) -> None:
    # kaindl.com wraps every .btn label with a trailing <span class="btn__icon">
    # containing an arrow SVG. The theme's .btn already emits its own arrow via
    # CSS, so leaving the imported span renders two arrows. Strip it
    # unconditionally.
    for span in list(soup.find_all("span", class_="btn__icon")):
        if isinstance(span, Tag):
            span.decompose()

    for use in list(soup.find_all("use")):
        if not isinstance(use, Tag):
            continue
        href = use.get("xlink:href") or use.get("href") or ""
        icon_id = _resolve_icon_id(href)
        if icon_id is None:
            continue
        ctx.icon_ids.add(icon_id)
        new_ref = f"{LOCAL_SPRITE}#{icon_id}"
        use["xlink:href"] = new_ref
        if use.has_attr("href"):
            use["href"] = new_ref

    # Make every unlabeled <svg> accessibility-clean as decoration.
    for svg in list(soup.find_all("svg")):
        if not isinstance(svg, Tag):
            continue
        if not svg.get("aria-label") and not svg.get("aria-labelledby"):
            svg["aria-hidden"] = "true"
            svg["focusable"] = "false"
