"""Generic orphan-pairing restructure across all 79 pages.

The initial import flattened most `text-image-content` / `teaser-banner` /
heading-with-cta kaindl.com blocks into pairs of sibling sections:

    [ PLAIN copy section (h2 + paragraphs) ][ PLAIN button-only section ]
    [ PLAIN copy section (h2 + paragraphs) ][ PLAIN image-only section ]
    [ PLAIN image-only section ][ PLAIN copy section (h2 + paragraphs) ]

This script walks every page and fuses those pairs into one modern primitive:

    - (copy) + (button) → append button into copy-section (kaindl-copy adopts
      the anchor; `.page-body .kaindl-copy a.btn` rule already styles it with
      proper top margin).
    - (copy) + (img)    → `.page-body__two-col--photo` (`--flip` alternating
      every even photo pair per page, skipping diagram images).
    - (img)  + (copy)   → same two-col, with image already on the left.

Skips any section that already uses a modern primitive (teaser, feature-list,
video, downloads, faq, two-col, product-grid, teaser-banner).

Idempotent; safe to re-run.
"""

from __future__ import annotations

import json
import re
import sys
from pathlib import Path

from bs4 import BeautifulSoup, NavigableString, Tag

REPO_ROOT = Path(__file__).resolve().parents[3]
PAGES_JSON = REPO_ROOT / "web" / "modules" / "custom" / "kaindl_pages" / "data" / "pages-content.en.json"

_MODERN_CLASS_RE = re.compile(
    r"page-body__two-col|collection-teaser|page-body__feature-list|"
    r"page-body__video|page-body__downloads|page-body__faq|"
    r"page-body__teaser-banner|page-body__product-grid|page-body__gallery"
)

_DIAGRAM_HINTS = ("diagramm", "kreislauf", "doppelkopf", "chart", "schema",
                   "grafik", "infografik", "icon", "symbol")


def _html_has_modern(sec: Tag) -> bool:
    return bool(_MODERN_CLASS_RE.search(str(sec.get("class") or "") + " " + " ".join(
        " ".join(t.get("class") or []) for t in sec.find_all(True)
    )))


def _first_heading(sec: Tag) -> Tag | None:
    return sec.find(["h2", "h3", "h4"])


def _section_kind(sec: Tag) -> str:
    if _html_has_modern(sec):
        return "MODERN"
    copy = sec.find(class_="kaindl-copy")
    btns = sec.find_all("a", class_="btn")
    imgs = sec.find_all("img")
    # Ignore empty wrappers
    if not copy and not btns and not imgs:
        return "EMPTY"
    # Copy with inline image
    if copy and any(copy.find(lambda t: t.name == "img") for _ in [0]) and copy.find("img"):
        # Fall through — image inside copy counts as COPY_IMG_INLINE
        return "COPY_IMG_INLINE"
    if copy and imgs:
        # img outside copy but section has both → rare
        return "COPY_IMG_INLINE"
    if copy and not imgs:
        # Copy-only. Classify by whether it has a heading and btns.
        has_h = bool(_first_heading(copy))
        if btns and not has_h:
            # Standalone button(s).
            return "BTN_ONLY"
        if has_h and btns:
            return "COPY_WITH_BTN"
        if has_h:
            return "COPY_H"
        if btns:
            return "BTN_ONLY"
        return "COPY_PLAIN"
    if imgs and not copy:
        # No kaindl-copy wrapper but image(s) present → IMG_ONLY.
        return "IMG_ONLY"
    if btns and not copy and not imgs:
        return "BTN_ONLY"
    return "OTHER"


def _is_diagram_img(src: str) -> bool:
    s = (src or "").lower()
    return any(h in s for h in _DIAGRAM_HINTS)


def _extract_btn_html(sec: Tag) -> str:
    """Return the outerHTML of the first `.btn` anchor; empty string otherwise."""
    a = sec.find("a", class_="btn")
    return str(a) if a else ""


def _merge_btn_into_copy(copy_sec: Tag, btn_html: str) -> None:
    """Append the button as a trailing child of the section's .kaindl-copy."""
    copy_div = copy_sec.find(class_="kaindl-copy")
    if not copy_div:
        return
    copy_div.append(BeautifulSoup(btn_html, "html.parser"))


def _build_photo_two_col(copy_sec: Tag, img_sec: Tag, flip: bool) -> BeautifulSoup:
    copy_div = copy_sec.find(class_="kaindl-copy")
    heading_el = _first_heading(copy_div) if copy_div else None
    headline = heading_el.get_text(" ", strip=True) if heading_el else ""
    img = img_sec.find("img")
    src = img.get("src") if img else ""
    alt = img.get("alt", "") if img else ""
    diagram = _is_diagram_img(src)

    # Build inner copy HTML from copy_div children (excluding the heading since
    # we'll re-emit it inside kaindl-copy ourselves — actually keep it inline).
    inner_parts = []
    for child in list(copy_div.children):
        inner_parts.append(str(child))
    inner_html = "".join(inner_parts)
    if not heading_el:
        # Fall back: wrap everything as-is
        inner_html = inner_html
    # Remove any h2 that got duplicated (we'll re-insert at top if missing)
    mods = ["grid", "grid--2", "items-center", "page-body__two-col"]
    if not diagram:
        mods.append("page-body__two-col--photo")
        if flip:
            mods.append("page-body__two-col--flip")
    html = (
        '<section class="page-body__section section-spacer">'
        f'<div class="{" ".join(mods)}">'
        f'<div class="kaindl-copy">{inner_html}</div>'
        f'<figure class="page-body__media"><img alt="{alt}" decoding="async" loading="lazy" src="{src}"/></figure>'
        '</div></section>'
    )
    return BeautifulSoup(html, "html.parser")


def process_page(body_html: str) -> tuple[str, dict]:
    report = {"btn_pairs": 0, "img_pairs": 0}
    soup = BeautifulSoup(body_html, "html.parser")
    article = soup.find("article", class_="page-body")
    if not article:
        return body_html, report

    changed = True
    photo_counter = 0
    # Iterate until stable to handle cascaded pairings.
    safety = 0
    while changed and safety < 20:
        changed = False
        safety += 1
        sections = list(article.find_all("section", recursive=False))
        for idx, sec in enumerate(sections):
            nxt = sections[idx + 1] if idx + 1 < len(sections) else None
            prv = sections[idx - 1] if idx - 1 >= 0 else None
            k = _section_kind(sec)
            # Pairing 1: COPY_H / COPY_WITH_BTN + BTN_ONLY (sibling)
            if k in ("COPY_H", "COPY_WITH_BTN") and nxt is not None and _section_kind(nxt) == "BTN_ONLY":
                btn_html = _extract_btn_html(nxt)
                if btn_html:
                    _merge_btn_into_copy(sec, btn_html)
                    nxt.decompose()
                    report["btn_pairs"] += 1
                    changed = True
                    break  # restart scan
            # Pairing 2: COPY_H + IMG_ONLY (sibling)
            if k in ("COPY_H", "COPY_WITH_BTN", "COPY_PLAIN") and nxt is not None and _section_kind(nxt) == "IMG_ONLY":
                img = nxt.find("img")
                if img:
                    flip = (photo_counter % 2 == 1)
                    new_frag = _build_photo_two_col(sec, nxt, flip)
                    sec.replace_with(new_frag)
                    nxt.decompose()
                    photo_counter += 1
                    report["img_pairs"] += 1
                    changed = True
                    break
            # Pairing 3: IMG_ONLY + COPY_H (reverse)
            if k == "IMG_ONLY" and nxt is not None and _section_kind(nxt) in ("COPY_H", "COPY_WITH_BTN"):
                img = sec.find("img")
                if img:
                    flip = (photo_counter % 2 == 1)
                    new_frag = _build_photo_two_col(nxt, sec, flip)
                    nxt.replace_with(new_frag)
                    sec.decompose()
                    photo_counter += 1
                    report["img_pairs"] += 1
                    changed = True
                    break

    # Pass 4: convert COPY_IMG_INLINE sections (img inside .kaindl-copy) to
    # two-col--photo. We handle these after the sibling-pairing pass so we
    # don't double-transform.
    sections = list(article.find_all("section", recursive=False))
    for sec in sections:
        if _section_kind(sec) != "COPY_IMG_INLINE":
            continue
        copy_div = sec.find(class_="kaindl-copy")
        if not copy_div:
            continue
        img = copy_div.find("img")
        if not img:
            continue
        img_src = img.get("src") or ""
        img_alt = img.get("alt") or ""
        heading_el = _first_heading(copy_div)
        headline = heading_el.get_text(" ", strip=True) if heading_el else ""
        if not headline:
            continue
        # Pull img out of copy_div.
        img.extract()
        inner_parts = []
        for child in list(copy_div.children):
            # Strip empty NavigableString whitespace
            if isinstance(child, NavigableString) and not str(child).strip():
                continue
            inner_parts.append(str(child))
        inner_html = "".join(inner_parts)
        diagram = _is_diagram_img(img_src)
        flip = (photo_counter % 2 == 1)
        mods = ["grid", "grid--2", "items-center", "page-body__two-col"]
        if not diagram:
            mods.append("page-body__two-col--photo")
            if flip:
                mods.append("page-body__two-col--flip")
        new_frag = BeautifulSoup(
            '<section class="page-body__section section-spacer">'
            f'<div class="{" ".join(mods)}">'
            f'<div class="kaindl-copy">{inner_html}</div>'
            f'<figure class="page-body__media"><img alt="{img_alt}" decoding="async" loading="lazy" src="{img_src}"/></figure>'
            '</div></section>',
            "html.parser"
        )
        sec.replace_with(new_frag)
        if not diagram:
            photo_counter += 1
        report["img_pairs"] += 1

    if report["btn_pairs"] or report["img_pairs"]:
        return str(soup), report
    return body_html, report


def main() -> int:
    with PAGES_JSON.open(encoding="utf-8") as f:
        data = json.load(f)
    totals = {"btn_pairs": 0, "img_pairs": 0, "pages_changed": 0}
    per_page = []
    for e in data["pages"]:
        body = e.get("body", "") or ""
        if not body or "page-body" not in body:
            continue
        new_body, rep = process_page(body)
        if new_body != body:
            e["body"] = new_body
            totals["pages_changed"] += 1
            totals["btn_pairs"] += rep["btn_pairs"]
            totals["img_pairs"] += rep["img_pairs"]
            per_page.append((e.get("source_key"), rep))
    with PAGES_JSON.open("w", encoding="utf-8") as f:
        json.dump(data, f, ensure_ascii=False, indent=2)
    print(f"[done] {totals['pages_changed']} pages updated; "
          f"{totals['btn_pairs']} btn pairings, {totals['img_pairs']} img pairings\n")
    for sk, rep in per_page:
        print(f"  btn={rep['btn_pairs']:2} img={rep['img_pairs']:2}  {sk}")
    return 0


if __name__ == "__main__":
    sys.exit(main())
