"""Rule 3: drop legacy typography & BEM-leftover classes; promote ``.f-bold`` to ``<strong>``.

Drops classes by exact match (``f-bold``, ``js-lazy``) and by prefix
(``color-…``, ``ft<N>``, ``text-image-content__…``, and every BEM-child
remnant left behind by preceding upgrade rules). Also unwraps
``div.formatted-text`` wrappers.

The prefix list is intentionally additive: as new upgrade rules cover more
patterns, their __child leftover classes are added here so the parity verifier
stays clean.
"""

from __future__ import annotations

import re

from bs4 import BeautifulSoup, Tag

from . import TransformContext


_DROP_EXACT = {
    "f-bold", "js-lazy", "f-light", "upper", "image",
    # Legacy image / references frames — their container <div>s are
    # unwrapped by upgrade_text_image; when the class sits on a non-div
    # element (e.g. ``<a class="references-grid__item-image image-wrapper">``)
    # it survives as a leaf class. Strip it uniformly here.
    "image-wrapper", "image-wrapper--spread", "image-wrapper--square",
    "image-wrapper--round", "image-wrapper--boxed",
}

_DROP_PREFIXES = (
    # Typography utilities from the source CMS.
    "color-",
    # BEM leftovers from elements that stayed after their parent wrapper was
    # unwrapped or upgraded. Safe because any __child class that would be
    # caught here is purely cosmetic — the parent block is already replaced
    # by its theme equivalent.
    "text-image-content__",
    "rich-bullet-list__",
    "rich-bullet-list-",
    "basic-slider__",
    "caption-slider__",
    "content-carousel__",
    "video-slider__",
    "faq-list__",
    "testimonials-slider__",
    "job-list__",
    "product-detail__downloads-",
    "image-wrapper__",    "references-products__",
    "references-grid__",
    "references-grid-",
    # NOTE: Keep only the plural `collection-teasers__` (the grid block on the
    # home page). The singular `collection-teaser__` is the reusable banner
    # snippet editors paste into Basic Page bodies — do NOT add it here.
    "collection-teasers__",
    "header-image__",
    "breadcrumb-navigation__",
    "scope-navigation__",
    "svg-icon--",
    "swiper-",
    "page-intro__",
)

_FT_PATTERN = re.compile(r"^ft\d+$")


def _clean_classes(tag: Tag) -> None:
    classes = tag.get("class") or []
    kept = []
    for cls in classes:
        if cls in _DROP_EXACT:
            continue
        if any(cls.startswith(pfx) for pfx in _DROP_PREFIXES):
            continue
        if _FT_PATTERN.match(cls):
            continue
        kept.append(cls)
    if kept:
        tag["class"] = kept
    elif "class" in tag.attrs:
        del tag["class"]


def transform(soup: BeautifulSoup, ctx: TransformContext) -> None:
    # Promote <span class="f-bold">X</span> → <strong>X</strong>.
    for span in list(soup.find_all("span")):
        if not isinstance(span, Tag):
            continue
        if "f-bold" in (span.get("class") or []):
            span.name = "strong"
            _clean_classes(span)

    # Unwrap .formatted-text wrappers — purely stylistic.
    for div in list(soup.find_all("div", class_="formatted-text")):
        if isinstance(div, Tag):
            div.unwrap()

    # Strip utility classes everywhere else.
    for tag in list(soup.find_all(True)):
        if isinstance(tag, Tag) and tag.has_attr("class"):
            _clean_classes(tag)
