"""Rule 17 (final pass): wrap body content into the canonical page-body skeleton.

Output shape:
    <article class="page-body" data-transformed="v1">
      <section class="page-body__section section-spacer">
        <div class="container--narrow">
          <div class="kaindl-copy">
            ... consecutive prose (h2/h3/p/ul/ol/figure/blockquote) ...
          </div>
        </div>
      </section>
      <section class="page-body__section section-spacer">
        <div class="container">
          ... a single pre-upgraded block such as .page-body__two-col ...
        </div>
      </section>
      ...
    </article>

Grouping rule:
- Consecutive prose elements land in one ``.kaindl-copy`` inside one
  ``.page-body__section`` + ``.container--narrow``.
- Every pre-upgraded ``.page-body__*`` block gets its own ``.page-body__section``
  + ``.container`` (full width) so its own layout tokens govern the grid.

Idempotent: if an ``<article class="page-body" data-transformed="v1">`` root is
already present, the rule no-ops.
"""

from __future__ import annotations

from bs4 import BeautifulSoup, NavigableString, Tag

from . import TRANSFORM_VERSION, TransformContext


_PROSE_TAGS = {
    "h1", "h2", "h3", "h4", "h5", "h6",
    "p", "ul", "ol", "dl",
    "blockquote", "pre", "figure", "table",
    "hr",
}


def transform(soup: BeautifulSoup, ctx: TransformContext) -> None:
    body = soup.body if soup.body else soup

    # Idempotency sentinel — already wrapped, do nothing.
    if _already_wrapped(body):
        return

    # Strip whitespace-only nodes and empty divs leftover from prior rules.
    _prune_empty_divs(body)

    content_nodes = [n for n in list(body.children) if _is_content(n)]
    if not content_nodes:
        return

    article = soup.new_tag("article", **{"class": "page-body", "data-transformed": TRANSFORM_VERSION})

    pending_prose: list = []

    def _flush_prose() -> None:
        if not pending_prose:
            return
        section = _build_prose_section(soup, pending_prose)
        article.append(section)
        pending_prose.clear()

    for node in content_nodes:
        if _is_prose_node(node):
            pending_prose.append(node.extract())
            continue

        _flush_prose()
        article.append(_build_block_section(soup, node.extract()))

    _flush_prose()

    body.clear()
    body.append(article)


def _already_wrapped(body: Tag) -> bool:
    existing = body.find("article", class_="page-body")
    return isinstance(existing, Tag) and existing.get("data-transformed") == TRANSFORM_VERSION


def _prune_empty_divs(body: Tag) -> None:
    changed = True
    while changed:
        changed = False
        for div in list(body.find_all("div")):
            if not isinstance(div, Tag):
                continue
            if div.get_text(strip=True):
                continue
            if div.find(_is_void_content):
                continue
            div.decompose()
            changed = True


def _is_void_content(tag: Tag) -> bool:
    return isinstance(tag, Tag) and tag.name in {"img", "iframe", "video", "audio", "svg", "canvas", "hr", "source"}


def _is_content(node) -> bool:
    if isinstance(node, NavigableString):
        return bool(str(node).strip())
    if not isinstance(node, Tag):
        return False
    if node.get_text(strip=True):
        return True
    # A bare void element at top level (e.g. a lone <img>) is itself content,
    # even though it has no text and no void descendants.
    if _is_void_content(node):
        return True
    return node.find(_is_void_content) is not None


def _is_prose_node(node) -> bool:
    if isinstance(node, NavigableString):
        return bool(str(node).strip())
    if not isinstance(node, Tag):
        return False
    return node.name in _PROSE_TAGS


def _build_prose_section(soup: BeautifulSoup, nodes: list) -> Tag:
    # Layout/page.html.twig already wraps page.content in a .container, so the
    # per-section wrapper would just duplicate horizontal padding/max-width.
    # Copy width is handled via ``.page-body .kaindl-copy { max-width: … }``.
    section = soup.new_tag("section", **{"class": "page-body__section section-spacer"})
    copy_wrap = soup.new_tag("div", **{"class": "kaindl-copy"})
    for node in nodes:
        copy_wrap.append(node)
    section.append(copy_wrap)
    return section


def _build_block_section(soup: BeautifulSoup, block: Tag) -> Tag:
    section = soup.new_tag("section", **{"class": "page-body__section section-spacer"})
    section.append(block)
    return section
