"""Body transform rules for kaindl_pages seed modernization.

Each rule is a pure function ``transform(soup, ctx)`` that mutates ``soup``
in place. The driver calls rules in ``RULE_ORDER``. Idempotency is the
rule's responsibility (check a sentinel before acting).

Rule ordering (deviates from plan sketch intentionally):
    Content-specific upgrades MUST run before ``upgrade_sections``,
    because the final pass wraps whatever is still bare prose into a
    default ``.page-body__section`` + ``.container--narrow``. Any content
    upgrade that runs later would be inside that wrapper, not the correct
    wide-container / grid structure its pattern wants.
"""

from __future__ import annotations

from dataclasses import dataclass, field
from typing import Any, Callable, Protocol

from bs4 import BeautifulSoup


@dataclass
class HeaderExtraction:
    """Extracted page-header field values, routed to field_page_header_*."""

    kicker: str = ""  # Plain string only. field_page_header_kicker is string_textfield.
    intro: str = ""   # HTML allowed. field_page_header_intro is text_long (full_html).
    source_title: str = ""  # For dedup check vs node.title; never written to a field.


@dataclass
class TransformContext:
    """Per-page state shared across rules."""

    source_key: str
    alias: str
    title: str
    slug: str

    header: HeaderExtraction = field(default_factory=HeaderExtraction)
    manifest_rows: list[dict[str, Any]] = field(default_factory=list)
    report_entries: list[dict[str, Any]] = field(default_factory=list)
    icon_ids: set[str] = field(default_factory=set)
    alt_review: list[dict[str, Any]] = field(default_factory=list)
    title_mismatch: dict[str, str] | None = None

    def log_unknown(self, rule: str, selector: str, snippet: str) -> None:
        self.report_entries.append(
            {
                "source_key": self.source_key,
                "rule": rule,
                "selector": selector,
                "snippet": snippet[:240],
            }
        )


class Rule(Protocol):
    def transform(self, soup: BeautifulSoup, ctx: TransformContext) -> None: ...


TRANSFORM_VERSION = "v1"


from . import (  # noqa: E402
    extract_header_fields,
    strip_bootstrap_cols,
    normalize_typography,
    dedupe_intro_from_body,
    strip_inline_svg_icons,
    sanitize_urls,
    migrate_images,
    upgrade_text_image,
    upgrade_rich_bullet_list,
    upgrade_downloads,
    upgrade_caption_slider,
    upgrade_content_carousel,
    upgrade_video,
    upgrade_faq,
    upgrade_testimonials,
    upgrade_job_list,
    upgrade_collapsible,
    upgrade_basic_slider,
    upgrade_collection_teasers,
    upgrade_contact_persons,
    upgrade_fact_tiles,
    upgrade_scope_navigation,
    harden_iframes,
    upgrade_sections,
    merge_heading_only_sections,
    unwrap_redundant_wrappers,
)


RULE_ORDER: list[tuple[str, Callable[[BeautifulSoup, TransformContext], None]]] = [
    # 1. Extract header fields + strip chrome blocks.
    ("extract_header_fields",    extract_header_fields.transform),
    # 2. Flatten Bootstrap grid/flex/swiper wrappers so content-specific rules
    #    see their target patterns at a predictable nesting depth. This does
    #    NOT touch the pattern-carrying classes (``.rich-bullet-list``, etc.).
    ("strip_bootstrap_cols",     strip_bootstrap_cols.transform),
    # 3. Content-specific upgrades. These run BEFORE upgrade_text_image so
    #    signals like ``.rich-bullet-list.content-element`` on the outer
    #    wrapper aren't destroyed by a premature ``.content-element`` unwrap.
    ("upgrade_rich_bullet_list", upgrade_rich_bullet_list.transform),
    ("upgrade_downloads",        upgrade_downloads.transform),
    ("upgrade_caption_slider",   upgrade_caption_slider.transform),
    ("upgrade_content_carousel", upgrade_content_carousel.transform),
    ("upgrade_video",            upgrade_video.transform),
    ("upgrade_faq",              upgrade_faq.transform),
    ("upgrade_testimonials",     upgrade_testimonials.transform),
    ("upgrade_job_list",         upgrade_job_list.transform),
    ("upgrade_collapsible",      upgrade_collapsible.transform),
    ("upgrade_basic_slider",     upgrade_basic_slider.transform),
    ("upgrade_collection_teasers", upgrade_collection_teasers.transform),
    ("upgrade_contact_persons",  upgrade_contact_persons.transform),
    ("upgrade_fact_tiles",       upgrade_fact_tiles.transform),
    ("upgrade_scope_navigation", upgrade_scope_navigation.transform),
    # 4. Generic structural unwraps and class cleanup — every remaining
    #    legacy wrapper / class is scrubbed here.
    ("upgrade_text_image",       upgrade_text_image.transform),
    ("normalize_typography",     normalize_typography.transform),
    # Remove body paragraphs that duplicate ctx.header.intro. Runs after
    # typography normalization so text comparison works on clean strings.
    ("dedupe_intro_from_body",   dedupe_intro_from_body.transform),
    ("strip_inline_svg_icons",   strip_inline_svg_icons.transform),
    # 5a. Scrub stray quote / backslash / whitespace from URL attributes.
    #     Runs before migrate_images so absolute-URL parsing there sees clean
    #     input, and so internal link parity stays stable.
    ("sanitize_urls",            sanitize_urls.transform),
    # 5b. Image URL migration. Runs late so every content-specific rule has
    #     already placed its ``<img>`` elements at the right nesting depth.
    ("migrate_images",           migrate_images.transform),
    # 5c. Iframe hardening — catches every <iframe> (including pre-existing
    #     Matterport / video embeds that didn't pass through upgrade_video)
    #     and fills title / loading / allowfullscreen gaps.
    ("harden_iframes",           harden_iframes.transform),
    # 6. Final canonical skeleton.
    ("upgrade_sections",         upgrade_sections.transform),
    # 7. After sections exist, fuse any heading-only `.page-body__section`
    #    into the section that follows it (the FAQ / gallery / feature-list
    #    / prose it actually belongs to). Runs last so it sees the canonical
    #    section tree.
    ("merge_heading_only_sections", merge_heading_only_sections.transform),
    # 8. Strip the intermediate `<section class="page-body__X-section">` that
    #    some content upgraders emit inside `.page-body__section`. These are
    #    structurally redundant once `upgrade_sections` has provided the
    #    outer wrapper; removing them flattens the DOM for screen readers.
    ("unwrap_redundant_wrappers", unwrap_redundant_wrappers.transform),
]
