"""Rule 2: flatten Bootstrap grid wrappers and flex utilities; keep children in place.

Unwraps, in repeated passes until stable:
- Bootstrap grid: ``.row``, ``.col-*``, ``.offset-*``, ``.container-fluid``, ``.container--padded``.
- Bootstrap flex utilities: ``.d-flex``, ``.flex-*`` (flex-column, flex-row, flex-grow-*, flex-shrink-*, flex-wrap).
- Responsive display helpers: ``.d-none``, ``.d-lg-block``, ``.d-md-*``, etc.
- Swiper wrappers that survive upgrade_basic_slider / upgrade_caption_slider:
  ``.swiper``, ``.swiper-wrapper``, ``.swiper-container``, ``.swiper-slide``.

All of these are structural-only — unwrapping preserves the content underneath.
"""

from __future__ import annotations

import re

from bs4 import BeautifulSoup, Tag

from . import TransformContext


_LEGACY_PATTERNS = [
    # Bootstrap grid.
    re.compile(r"^row$"),
    re.compile(r"^col(?:-|$)"),
    re.compile(r"^offset-"),
    re.compile(r"^container$"),
    re.compile(r"^container-fluid$"),
    re.compile(r"^container--padded$"),
    re.compile(r"^container--narrow$"),
    re.compile(r"^container--maxed$"),
    # Bootstrap flex utilities. Narrow patterns only — ``.items-center``,
    # ``.justify-between``, ``.text-center`` etc. are theme-owned utility
    # classes from layout.css that must survive.
    re.compile(r"^d-(?:flex|block|inline|inline-flex|inline-block|none)$"),
    re.compile(r"^d-(?:sm|md|lg|xl|xxl)-(?:flex|block|inline|inline-flex|inline-block|none)$"),
    re.compile(r"^flex-(?:column|row|grow-\d+|shrink-\d+|wrap|nowrap|fill)$"),
    re.compile(r"^justify-content-"),
    re.compile(r"^align-items-"),
    re.compile(r"^w-(?:25|50|75|100|auto)$"),
    # Swiper wrappers.
    re.compile(r"^swiper(?:-|$)"),
]


def _is_purely_legacy(tag: Tag) -> bool:
    """Return True only if EVERY class on the tag matches a legacy pattern.

    A tag like ``<div class="swiper-slide content-carousel__slider-item">``
    carries both ``swiper-slide`` (legacy) and ``content-carousel__slider-item``
    (content class that ``upgrade_content_carousel`` needs). Unwrapping the
    tag would destroy the content class and break the downstream rule. Only
    unwrap when the tag is purely structural.
    """
    classes = tag.get("class") or []
    if not classes:
        return False
    for cls in classes:
        if not any(pat.match(cls) for pat in _LEGACY_PATTERNS):
            return False
    return True


def transform(soup: BeautifulSoup, ctx: TransformContext) -> None:
    changed = True
    while changed:
        changed = False
        for tag in list(soup.find_all(True)):
            if not isinstance(tag, Tag):
                continue
            if tag.name not in {"div", "span", "section"}:
                continue
            if _is_purely_legacy(tag):
                tag.unwrap()
                changed = True
