"""Rule 1: extract page-header field values (kicker/intro) from body, strip header blocks.

Routes content to:
- ``ctx.header.kicker`` — plain string (field_page_header_kicker is string_textfield, 255 char cap).
- ``ctx.header.intro``  — HTML fragment (field_page_header_intro is text_long / full_html).
- ``ctx.title_mismatch`` — populated when the source <h1> text differs from ``node.title``.

Order matters: kicker + intro are captured from INSIDE the ``.header-image`` wrapper
BEFORE the wrapper itself is decomposed. A previous iteration stripped the wrapper
first and then tried to search an empty tree — fixed.

Stripped from body entirely:
- ``.header-image`` and its descendants (slides + breadcrumbs + any other chrome).
- ``.page-intro__media``.
- ``.breadcrumb-navigation*`` blocks that live outside the header (rare but defensive).
- The first ``<h1>`` if any survived.
- A leading ``<h2>`` whose text duplicates ``node.title`` (legal-page pattern).
"""

from __future__ import annotations

import re
from typing import Optional

from bs4 import BeautifulSoup, Tag

from . import TransformContext


# Sub-blocks inside ``.header-image`` that are always chrome — the page-header
# twig template renders their data from ``field_page_header_*``. These get
# DECOMPOSED (content discarded).
_HEADER_CHROME_CLASSES = (
    "header-image__intro",
    "header-image__image",
    "header-image__media",
    "header-image__basic-slider",
    "header-image__scroll-indicator",
    "header-image__headlines",
    "header-image__breadcrumbs",
    "page-intro__media",
)

# Any other ``.header-image__*`` element carries body content (e.g.
# ``.header-image__content`` and ``.header-image__teaser-text`` on 11decks —
# the template deliberately tucks body prose inside the header section). These
# get UNWRAPPED so their children land at body top level.
_HEADER_SUB_PREFIX = "header-image__"

_KICKER_CLASS_PATTERN = re.compile(r"(header-image__kicker|page-intro__kicker|^kicker$)")
_INTRO_CLASS_PATTERN = re.compile(r"(page-intro__text|header-image__content|\bpage-intro\b)")

# Reference-page pattern: a single ``<h2 class="header-image__headlines-secondary">``
# carries both the kicker (first sentence) and the intro (rest). Split on the
# first sentence terminator (``.``, ``!``, ``?``) whose next char is whitespace.
_HEADLINES_SECONDARY_CLASS = "header-image__headlines-secondary"
_SENTENCE_BOUNDARY = re.compile(r"(?<=[.!?])\s+")


def _normalize(text: str) -> str:
    return " ".join(text.split())


def _titles_match(a: str, b: str) -> bool:
    na = _normalize(a).lower().rstrip(".! ")
    nb = _normalize(b).lower().rstrip(".! ")
    return na != "" and na == nb


def _extract_from_header_scope(soup: BeautifulSoup, ctx: TransformContext) -> None:
    """Pull kicker + intro out of the .header-image block before the block itself is stripped."""
    header = soup.find(class_="header-image")
    if not isinstance(header, Tag):
        return

    # Reference-page structured h2: two sentences smashed together.
    secondary = header.find(class_=_HEADLINES_SECONDARY_CLASS)
    if isinstance(secondary, Tag):
        text = _normalize(secondary.get_text(" ", strip=True))
        if text:
            parts = _SENTENCE_BOUNDARY.split(text, maxsplit=1)
            first = parts[0].rstrip(".")
            rest = parts[1] if len(parts) > 1 else ""
            if not ctx.header.kicker and first:
                ctx.header.kicker = first[:255]
            if not ctx.header.intro and rest:
                ctx.header.intro = f"<p>{rest}</p>"

    # Fallback selectors for pages with explicit kicker / intro classes.
    if not ctx.header.kicker:
        node = header.find(class_=_KICKER_CLASS_PATTERN)
        if isinstance(node, Tag):
            text = _normalize(node.get_text(" ", strip=True))
            if text:
                ctx.header.kicker = text[:255]

    if not ctx.header.intro:
        node = header.find(class_=_INTRO_CLASS_PATTERN)
        if isinstance(node, Tag):
            # Prefer the nearest ``.formatted-text`` child so we pick up
            # EVERY <p> in the intro block (kaindl.com often splits the
            # intro across 2–3 paragraphs; grabbing only the first leaves
            # the rest to leak into body after the wrapper is unwrapped —
            # see /en/company/floor-house/).
            formatted = node.find(class_="formatted-text")
            source = formatted if isinstance(formatted, Tag) else node
            paragraphs = source.find_all("p")
            if paragraphs:
                ctx.header.intro = "".join(str(p) for p in paragraphs).strip()
                # Remove those paragraphs from the tree so the subsequent
                # ``header-image__*`` unwrap pass does not re-leak them.
                for p in paragraphs:
                    p.decompose()
            else:
                inner = source.decode_contents().strip()
                if inner:
                    ctx.header.intro = inner


def transform(soup: BeautifulSoup, ctx: TransformContext) -> None:
    # 1. Capture kicker + intro from within the .header-image block before it
    #    is decomposed. Idempotency on re-runs is preserved because ctx.header
    #    fields are seeded from the JSON on page load.
    _extract_from_header_scope(soup, ctx)

    # 2a. Decompose known chrome sub-blocks (intro / image / slider / scroll
    #     indicator / breadcrumbs / …). Their content is already in
    #     field_page_header_slides / node.title / field_page_header_kicker /
    #     field_page_header_intro.
    for class_name in _HEADER_CHROME_CLASSES:
        for tag in list(soup.find_all(class_=class_name)):
            if isinstance(tag, Tag):
                tag.decompose()

    # 2b. Unwrap any remaining ``.header-image__*`` elements — these are body
    #     content wrappers (``__content``, ``__teaser-text``, etc.) that nest
    #     prose inside the header section on some pages (11decks pattern).
    for tag in list(soup.find_all(True)):
        if not isinstance(tag, Tag):
            continue
        # An earlier decompose may have detached ``tag`` from the tree; BS4
        # nulls its attrs. Skip detached nodes.
        if tag.attrs is None or tag.parent is None:
            continue
        for cls in tag.get("class") or []:
            if cls.startswith(_HEADER_SUB_PREFIX):
                tag.unwrap()
                break
    # Now unwrap any ``.header-image`` wrapper whose chrome is gone but which
    # still holds legitimate body content (e.g. text blocks tucked inside).
    for tag in list(soup.find_all(class_="header-image")):
        if isinstance(tag, Tag):
            if tag.get_text(strip=True) or tag.find(True):
                tag.unwrap()
            else:
                tag.decompose()

    # 3. Strip any remaining body-level breadcrumb blocks (defensive — the
    #    header block usually owns them, but some pages put them separately).
    for tag in list(soup.find_all(class_=re.compile(r"\bbreadcrumb-navigation\b"))):
        tag.decompose()

    # 3b. Strip ``.scope-navigation`` — a sibling-page sub-menu the source CMS
    #     renders inside the body. This project's theme owns section navigation
    #     via Drupal's menu / breadcrumb blocks, so leaving it in body produces
    #     a duplicated menu. All of its ancestors are safe to decompose.
    for tag in list(soup.find_all(class_=re.compile(r"\bscope-navigation\b"))):
        tag.decompose()

    # 4. Fallback kicker capture for pages with no .header-image block.
    if not ctx.header.kicker:
        kicker_node = soup.find(class_=_KICKER_CLASS_PATTERN)
        if isinstance(kicker_node, Tag):
            text = _normalize(kicker_node.get_text(" ", strip=True))
            if text:
                ctx.header.kicker = text[:255]
            kicker_node.decompose()

    # 5. Fallback intro capture for pages with no .header-image block.
    if not ctx.header.intro:
        intro_container = soup.find(class_=_INTRO_CLASS_PATTERN)
        if isinstance(intro_container, Tag):
            target: Optional[Tag] = intro_container.find("p") or intro_container
            inner = target.decode_contents().strip()
            if inner:
                ctx.header.intro = inner
            intro_container.decompose()

    # 6. Record a title mismatch (if any) BEFORE stripping the <h1>, then strip it.
    first_h1 = soup.find("h1")
    if isinstance(first_h1, Tag):
        source_title = _normalize(first_h1.get_text(" ", strip=True))
        ctx.header.source_title = source_title
        if source_title and ctx.title and not _titles_match(source_title, ctx.title):
            ctx.title_mismatch = {"source_h1": source_title, "node_title": ctx.title}
        first_h1.decompose()

    # 7. Strip a leading redundant <h2> that duplicates node.title (legal pattern).
    if ctx.title:
        first_h2 = soup.find("h2")
        if isinstance(first_h2, Tag):
            text = _normalize(first_h2.get_text(" ", strip=True))
            if _titles_match(text, ctx.title):
                first_h2.decompose()
