"""Rule: remove body paragraphs that duplicate ``ctx.header.intro``.

``extract_header_fields`` pulls ``<p>…</p>`` intro markup out of the source
`.header-image` / `.page-intro` wrapper and routes it to
``field_page_header_intro``. On a lot of kaindl.com pages, the same sentence
is also the first `<p>` inside the first body section. Left alone, the
rendered page shows the intro twice — once centered in the page header and
once left-aligned at the top of the body.

This rule runs after ``normalize_typography`` so it can compare on clean text
(no ``<span class="f-bold">`` wrappers, utility classes, etc.) and before
``upgrade_sections`` so the body's <p> elements are still bare prose, not yet
wrapped in ``.kaindl-copy`` / ``.container``.

Matching is text-normalized: whitespace collapsed, tags stripped, lower-cased,
trailing punctuation trimmed. If a body `<p>` normalizes to one of the intro
paragraphs, or the full intro text is fully contained inside one body `<p>`,
that paragraph is decomposed.
"""

from __future__ import annotations

import re

from bs4 import BeautifulSoup, Tag

from . import TransformContext


def _norm(text: str) -> str:
    return re.sub(r"\s+", " ", re.sub(r"<[^>]+>", "", text or "")).strip().lower().rstrip(".!? ")


def transform(soup: BeautifulSoup, ctx: TransformContext) -> None:
    intro_raw = ctx.header.intro or ""
    intro_n = _norm(intro_raw)
    if len(intro_n) < 15:
        return

    intro_soup = BeautifulSoup(intro_raw, "html.parser")
    intro_paras = {_norm(str(p)) for p in intro_soup.find_all("p")}
    intro_paras.discard("")
    if not intro_paras:
        intro_paras = {intro_n}

    for p in list(soup.find_all("p")):
        if not isinstance(p, Tag):
            continue
        p_n = _norm(str(p))
        if not p_n:
            continue
        if p_n in intro_paras:
            p.decompose()
            continue
        # Close-match: full intro contained in this <p> and roughly same length
        # (handles the case where the body concatenates the intro into one <p>).
        if len(intro_n) > 30 and intro_n in p_n and abs(len(p_n) - len(intro_n)) < 10:
            p.decompose()
            continue
