"""Rule (final pass): fuse standalone heading-only `.page-body__section`s
into the section that follows them.

kaindl.com frequently lays out:

    <div class="content-element"><h2>Sales</h2></div>
    <div class="faq-list content-element"> … items … </div>

``upgrade_sections`` wraps each sibling into its own
``<section class="page-body__section section-spacer">``, so the h2 ends up
visually orphaned by a full section-spacer gap on both sides. This rule
reunites the heading with the section it belongs to (the FAQ / gallery /
feature-list / prose immediately after).

Runs LAST so it sees the canonical section skeleton produced by
``upgrade_sections``.
"""

from __future__ import annotations

from bs4 import BeautifulSoup, NavigableString, Tag

from . import TransformContext

_HEADING_TAGS = {"h2", "h3", "h4"}

_MODERN_CLASSES = (
    "page-body__two-col",
    "collection-teaser",
    "page-body__feature-list",
    "page-body__video",
    "page-body__downloads",
    "page-body__faq",
    "page-body__teaser-banner",
    "page-body__product-grid",
    "page-body__gallery",
)


def _is_heading_only_section(sec: Tag) -> tuple[bool, list[Tag]]:
    if sec.find(["img", "iframe", "video", "ul", "ol", "table", "figure"]):
        return (False, [])
    if sec.find("p"):
        return (False, [])
    if sec.find("a", class_="btn"):
        return (False, [])
    for cls in _MODERN_CLASSES:
        if sec.select_one("." + cls):
            return (False, [])
    headings = sec.find_all(_HEADING_TAGS)
    if not headings:
        return (False, [])
    for el in sec.find_all(True):
        if el in headings or el.name in _HEADING_TAGS:
            continue
        direct_text = "".join(t for t in el.find_all(string=True, recursive=False))
        if direct_text.strip():
            return (False, [])
    return (True, headings)


def transform(soup: BeautifulSoup, ctx: TransformContext) -> None:
    article = soup.find("article", class_="page-body") or soup
    guard = 0
    changed = True
    while changed and guard < 50:
        guard += 1
        changed = False
        sections = [s for s in article.children if isinstance(s, Tag) and s.name == "section"]
        for idx, sec in enumerate(sections):
            if idx + 1 >= len(sections):
                break
            ok, headings = _is_heading_only_section(sec)
            if not ok:
                continue
            target = sections[idx + 1]
            extracted = [h.extract() for h in headings]
            for h in reversed(extracted):
                target.insert(0, h)
            sec.decompose()
            changed = True
            break
