"""Rule: ``.text-image-content`` → ``.page-body__two-col`` grid or bare prose.

A ``.text-image-content`` section can carry any sequence of inner
``.text-image-content__section--text`` and
``.text-image-content__section--image`` blocks. We walk them in document
order and pair adjacent ``image + text`` (either order) into a
``.page-body__two-col`` grid. Solo ``--text`` blocks become a
``.kaindl-copy`` div; solo ``--image`` blocks become a
``<figure class="page-body__media">``.

Two-col output:

    <div class="grid grid--2 items-center page-body__two-col">
      <div class="kaindl-copy"><h2>…</h2><p>…</p></div>
      <figure class="page-body__media"><img …></figure>
    </div>

After the ordered replace, Pass 2 unwraps any residual legacy wrappers so
``upgrade_sections`` can group the resulting blocks into ``page-body__section``
containers.
"""

from __future__ import annotations

import re

from bs4 import BeautifulSoup, Tag

from . import TransformContext


_UNWRAP_CLASSES = (
    # Residual wrappers left behind when a .text-image-content has sub-blocks
    # we didn't pair (e.g. orphan --text) or image-wrapper frames around <picture>.
    "text-image-content__text",
    "text-image-content__section--text",
    "text-image-content__section--image",
    "text-image-content__section",
    "text-image-content__image",
    "text-image-content",
    "content-element",
    "image-wrapper",
    "image-wrapper--spread",
    "image-wrapper--square",
    "image-wrapper--round",
    "image-wrapper--boxed",
    "references-products",
    "references-products__item-text",
    "references-products__item-image-wrapper",
    "references-products__items",
    # ``.collection-teaser`` (singular — hero-style banner, different from the
    # plural ``.collection-teasers`` grid handled by upgrade_collection_teasers).
    # Unwrap all of its scaffolding so the image/title/prose/CTA flow as bare
    # content and land in a default prose section.
    "collection-teaser",
    "collection-teaser__image-curtain-wrapper",
    "collection-teaser__image-curtain",
    "collection-teaser__image-curtain-content",
    "collection-teaser__image-wrapper",
    "collection-teaser__box",
)

_UNWRAP_TAG_NAMES = {"div", "section"}

_SECTION_CLASS_RE = re.compile(r"^text-image-content__(?:section(?:--text|--image)?|image)$")

# Maximum prose length (characters, whitespace-normalized) for a text block
# to be paired side-by-side with an image. Anything longer would be visually
# cramped at 50% width — render stacked instead (image above, prose below).
_PAIR_PROSE_BUDGET = 900


def transform(soup: BeautifulSoup, ctx: TransformContext) -> None:
    # Pass 1: for every .text-image-content, emit an in-order sequence of
    # two-col grids + solo blocks corresponding to its child --text / --image
    # sub-sections.
    for outer in list(soup.find_all(class_="text-image-content")):
        if not isinstance(outer, Tag):
            continue
        if outer.attrs is None or outer.parent is None:
            continue
        _transform_outer(outer, soup)

    # Pass 2: unwrap every residual legacy wrapper. A previous pass may have
    # detached descendants mid-iteration, which can null their attrs — guard
    # against that.
    for cls in _UNWRAP_CLASSES:
        for tag in list(soup.find_all(class_=cls)):
            if not isinstance(tag, Tag):
                continue
            if tag.attrs is None or tag.parent is None:
                continue
            if tag.name not in _UNWRAP_TAG_NAMES:
                continue
            tag.unwrap()


def _transform_outer(outer: Tag, soup: BeautifulSoup) -> None:
    # Walk all __section-- children in document order. BS4's find_all with a
    # compiled class pattern keeps source order.
    sub_sections = []
    for el in outer.find_all(class_=_SECTION_CLASS_RE):
        if not isinstance(el, Tag):
            continue
        classes = el.get("class") or []
        if "text-image-content__section--text" in classes:
            sub_sections.append(("text", el))
        elif "text-image-content__section--image" in classes or "text-image-content__image" in classes:
            sub_sections.append(("image", el))

    if not sub_sections:
        return

    produced: list[Tag] = []
    i = 0
    while i < len(sub_sections):
        kind, el = sub_sections[i]
        # Pair with the neighbor if (a) the pair is (text, image) or
        # (image, text) AND (b) the text block is short enough to sit
        # comfortably at 50% width. Legal/FAQ-style pages with long prose
        # paired with a decorative hero image are emitted stacked instead.
        if i + 1 < len(sub_sections) and sub_sections[i + 1][0] != kind:
            other_kind, other_el = sub_sections[i + 1]
            if kind == "text":
                text_el, image_el = el, other_el
            else:
                text_el, image_el = other_el, el
            if _text_fits_two_col(text_el):
                produced.append(_build_two_col(text_el, image_el, soup))
                i += 2
                continue
        # Solo block.
        if kind == "text":
            produced.append(_build_copy(el, soup))
        else:
            produced.append(_build_figure(el, soup))
        i += 1

    if not produced:
        return

    # Insert the new blocks AFTER the outer section, then remove the outer.
    parent = outer.parent
    if parent is None:
        return
    insert_after = outer
    for block in produced:
        insert_after.insert_after(block)
        insert_after = block
    outer.decompose()


def _text_fits_two_col(text_el: Tag) -> bool:
    prose = " ".join(text_el.get_text(" ", strip=True).split())
    return len(prose) <= _PAIR_PROSE_BUDGET


def _build_two_col(text_el: Tag, image_el: Tag, soup: BeautifulSoup) -> Tag:
    grid = soup.new_tag("div", **{"class": "grid grid--2 items-center page-body__two-col"})
    grid.append(_build_copy(text_el, soup))
    grid.append(_build_figure(image_el, soup))
    return grid


def _build_copy(text_el: Tag, soup: BeautifulSoup) -> Tag:
    # Walk up to the nearest ``.col-*`` wrapper so we capture CTA buttons
    # that sit as siblings of ``__section--text`` inside the same column
    # (common on product landing pages where each card has ``text +
    # button + image`` siblings). If no col-* ancestor exists — because
    # strip_bootstrap_cols already unwrapped it — fall back to the text_el
    # itself.
    copy_root = text_el
    cur = text_el.parent
    depth = 0
    while cur is not None and getattr(cur, "name", None) == "div" and depth < 4:
        classes = cur.get("class") or []
        if any(c.startswith("col-") or c.startswith("col ") or c == "col" for c in classes):
            copy_root = cur
            break
        if any(c in ("text-image-content", "row", "container-fluid") or c.startswith("text-image-content__section") for c in classes):
            break
        cur = cur.parent
        depth += 1

    copy = soup.new_tag("div", **{"class": "kaindl-copy"})
    for child in list(copy_root.children):
        if isinstance(child, Tag):
            copy.append(child.extract())
    return copy


def _build_figure(image_el: Tag, soup: BeautifulSoup) -> Tag:
    figure = soup.new_tag("figure", **{"class": "page-body__media"})
    img = image_el.find("img")
    if isinstance(img, Tag):
        figure.append(img.extract())
    return figure
