"""Shared helpers for page-body restructure scripts."""

from __future__ import annotations

import json
import re
from pathlib import Path
from typing import Iterable

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"

# Filename hints that mark a figure as a diagram, not a photo (so --photo
# variant should NOT be applied — diagrams render best without drop-shadow /
# cover-cropping).
_DIAGRAM_HINTS = (
    "diagramm",
    "kreislauf",
    "doppelkopf",
    "chart",
    "schema",
    "grafik",
    "infografik",
    "icon",
    "symbol",
)


def load_pages() -> dict:
    with PAGES_JSON.open(encoding="utf-8") as f:
        return json.load(f)


def save_pages(data: dict) -> None:
    with PAGES_JSON.open("w", encoding="utf-8") as f:
        json.dump(data, f, ensure_ascii=False, indent=2)


def pages_by_key(data: dict) -> dict[str, dict]:
    return {(e.get("source_key") or "").rstrip("/"): e for e in data["pages"]}


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


def body_sections(body_html: str) -> tuple[BeautifulSoup, Tag, list[Tag]]:
    """Parse a page body and return (soup, article_wrapper, section_list)."""
    soup = BeautifulSoup(body_html, "html.parser")
    article = soup.find("article", class_="page-body")
    sections = list(article.find_all("section", recursive=False)) if article else []
    return soup, article, sections


def sec_heading(sec: Tag) -> str:
    h = sec.find(["h2", "h3"])
    return (h.get_text(" ", strip=True) if h else "").strip()


def strip_empty_paragraphs(html: str) -> str:
    return re.sub(r"<p>\s*(?:&nbsp;|\xa0|\s)*\s*</p>", "", html)


def copy_inner_excluding(section: Tag, drop_tags: Iterable[str] = ("h2", "h3", "img"),
                          drop_btns: bool = True) -> str:
    """Return the inner HTML of the first `.kaindl-copy` with supplied tags
    (and optionally `<a.btn>` anchors) removed. Whitespace-only text nodes are
    skipped. Runs of `<p>&nbsp;</p>` are collapsed."""
    copy_div = section.find(class_="kaindl-copy")
    if not copy_div:
        return ""
    out_parts = []
    for child in copy_div.children:
        name = getattr(child, "name", None)
        if name in drop_tags:
            continue
        if drop_btns and name == "a":
            if "btn" in (child.get("class") or []):
                continue
        if isinstance(child, NavigableString) and not str(child).strip():
            continue
        out_parts.append(str(child))
    return strip_empty_paragraphs("".join(out_parts))


def build_two_col(soup: BeautifulSoup, headline: str, body_inner_html: str,
                   img_src: str, img_alt: str = "",
                   photo: bool = False, flip: bool = False) -> Tag:
    mods = ["grid", "grid--2", "items-center", "page-body__two-col"]
    if photo:
        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"><h2>{headline}</h2>{body_inner_html}</div>'
        f'<figure class="page-body__media"><img alt="{img_alt}" decoding="async" loading="lazy" src="{img_src}"/></figure>'
        '</div></section>'
    )
    return BeautifulSoup(html, "html.parser")


def build_cta_two_col(soup: BeautifulSoup, headline: str, body_inner_html: str,
                       btn_html: str) -> Tag:
    html = (
        '<section class="page-body__section section-spacer">'
        '<div class="page-body__two-col page-body__two-col--cta">'
        f'<div class="kaindl-copy"><h2>{headline}</h2>{body_inner_html}</div>'
        f'<div class="page-body__two-col__cta">{btn_html}</div>'
        '</div></section>'
    )
    return BeautifulSoup(html, "html.parser")


def build_collection_teaser(soup: BeautifulSoup, headline: str,
                              body_inner_html: str, img_src: str) -> Tag:
    html = (
        '<section class="page-body__section section-spacer">'
        '<div class="collection-teaser content-element" data-home-animate="true">'
          '<div class="collection-teaser__layout">'
            '<div class="collection-teaser__media">'
              '<div class="collection-teaser__image-curtain-wrapper">'
                '<div class="collection-teaser__image-curtain">'
                  '<div class="collection-teaser__image-curtain-content">'
                    '<figure class="collection-teaser__image-wrapper">'
                      f'<img class="collection-teaser__image" alt="" decoding="async" loading="lazy" src="{img_src}"/>'
                    '</figure>'
                  '</div></div></div></div>'
            '<div class="collection-teaser__body">'
              '<div class="collection-teaser__box">'
                f'<h2 class="collection-teaser__box-headline">{headline}</h2>'
                f'<div class="collection-teaser__box-text">{body_inner_html}</div>'
              '</div></div>'
          '</div>'
        '</div></section>'
    )
    return BeautifulSoup(html, "html.parser")


def build_teaser_banner(soup: BeautifulSoup, headline: str,
                         body_inner_html: str, btn_html: str) -> Tag:
    html = (
        '<section class="page-body__section section-spacer">'
        '<div class="page-body__teaser-banner">'
          f'<h2 class="page-body__teaser-banner__headline">{headline}</h2>'
          f'<div class="page-body__teaser-banner__text">{body_inner_html}</div>'
          f'<div class="page-body__teaser-banner__cta">{btn_html}</div>'
        '</div></section>'
    )
    return BeautifulSoup(html, "html.parser")


def classify_section(sec: Tag) -> str:
    """Return one of PLAIN_COPY, COPY_IMG_INLINE, COPY_WITH_BTN, IMG_ONLY,
    TWO_COL, TEASER, FEATURE, VIDEO, TEASER_BANNER, OTHER."""
    if sec.select_one(".page-body__two-col"):
        return "TWO_COL"
    if sec.select_one(".collection-teaser"):
        return "TEASER"
    if sec.select_one(".page-body__feature-list"):
        return "FEATURE"
    if sec.select_one(".page-body__video, .page-body__videos"):
        return "VIDEO"
    if sec.select_one(".page-body__teaser-banner"):
        return "TEASER_BANNER"
    if sec.select_one(".page-body__downloads"):
        return "DOWNLOADS"
    if sec.select_one(".page-body__faq"):
        return "FAQ"
    if sec.select_one(".page-body__gallery"):
        return "GALLERY"

    copy_div = sec.find(class_="kaindl-copy")
    has_img_in_copy = bool(copy_div and copy_div.find("img"))
    has_btn = bool(sec.find("a", class_="btn"))
    direct_img = sec.find("img", recursive=False)
    # descendants that aren't inside a component
    any_img = bool(sec.find("img"))

    if copy_div and has_img_in_copy:
        return "COPY_IMG_INLINE"
    if copy_div and has_btn and not any_img:
        return "COPY_WITH_BTN"
    if copy_div:
        return "PLAIN_COPY"
    if any_img and not copy_div:
        return "IMG_ONLY"
    return "OTHER"


def extract_img_src(sec: Tag) -> str | None:
    img = sec.find("img")
    return img.get("src") if img else None


def extract_heading_and_copy(sec: Tag) -> tuple[str, str]:
    h = sec.find(["h2", "h3"])
    headline = h.get_text(" ", strip=True) if h else ""
    body_inner = copy_inner_excluding(sec)
    return headline, body_inner


def replace_single(orig: Tag, new_fragment: BeautifulSoup) -> None:
    """Replace `orig` section with the new fragment, preserving document
    structure. Safe even if the fragment has a root."""
    orig.replace_with(new_fragment)
