"""Fuse standalone heading-only sections into the section that follows them.

A "heading-only" section contains nothing but an `<h2>`/`<h3>`/`<h4>` inside
an otherwise-empty `.kaindl-copy` (or directly inside the section). On the
rendered page they inherit `.page-body__section`'s `section-spacer` gap on
both sides — the heading sits in its own isolated band, detached from the
FAQ / gallery / feature-list / copy it actually belongs to.

Example (FAQ page, before):
  <section class="page-body__section section-spacer">
    <div class="kaindl-copy"><h2>Sales</h2></div>
  </section>
  <section class="page-body__section section-spacer">
    <div class="page-body__faq"> … items … </div>
  </section>

After:
  <section class="page-body__section section-spacer">
    <h2>Sales</h2>
    <div class="page-body__faq"> … items … </div>
  </section>

Idempotent. Runs across every page in `pages-content.en.json`.
"""

from __future__ import annotations

import json
import sys
from pathlib import Path
from typing import Iterable

from bs4 import BeautifulSoup, NavigableString, Tag

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

_HEADING_TAGS = {"h2", "h3", "h4"}


def _meaningful_children(container: Tag) -> list[Tag]:
    """Tag children with real content (skip whitespace-only text nodes)."""
    out = []
    for child in container.children:
        if isinstance(child, NavigableString):
            if str(child).strip():
                out.append(child)
            continue
        out.append(child)
    return out


def _is_heading_only_section(sec: Tag) -> tuple[bool, list[Tag]]:
    """Return (True, [heading_tags]) if this section has only heading
    element(s) as meaningful content; (False, []) otherwise."""
    if sec.find(["img", "iframe", "video", "ul", "ol", "table", "figure"]):
        return (False, [])
    if sec.find("p"):
        return (False, [])
    if sec.find("a", class_="btn"):
        return (False, [])
    for cls in ("page-body__two-col", "collection-teaser", "page-body__feature-list",
                 "page-body__video", "page-body__downloads", "page-body__faq",
                 "page-body__teaser-banner", "page-body__product-grid", "page-body__gallery"):
        if sec.select_one("." + cls):
            return (False, [])
    headings = sec.find_all(_HEADING_TAGS)
    if not headings:
        return (False, [])
    # Make sure no other meaningful text sits alongside them.
    # Walk every element with text — if text is not inside one of the headings, reject.
    for el in sec.find_all(True):
        if el in headings:
            continue
        if el.name in _HEADING_TAGS:
            continue
        txt = "".join(t for t in el.find_all(string=True, recursive=False))
        if txt.strip():
            return (False, [])
    return (True, headings)


def process_page(body_html: str) -> tuple[str, int]:
    soup = BeautifulSoup(body_html, "html.parser")
    art = soup.find("article", class_="page-body")
    if not art:
        return body_html, 0
    changed = True
    merges = 0
    guard = 0
    while changed and guard < 50:
        guard += 1
        changed = False
        sections = [s for s in art.children if isinstance(s, Tag) and s.name == "section"]
        for idx, sec in enumerate(sections):
            if idx + 1 >= len(sections):
                break
            ok, headings = _is_heading_only_section(sec)
            if not ok:
                continue
            target = sections[idx + 1]
            # Extract the heading tags (detached from sec).
            extracted = [h.extract() for h in headings]
            # Prepend them to `target` in order.
            for h in reversed(extracted):
                target.insert(0, h)
            sec.decompose()
            merges += 1
            changed = True
            break  # restart scan
    if merges:
        return str(soup), merges
    return body_html, 0


def main(argv: Iterable[str] = ()) -> int:
    with POST_JSON.open(encoding="utf-8") as f:
        data = json.load(f)
    total_merges = 0
    pages_changed = 0
    per_page = []
    for e in data["pages"]:
        body = e.get("body", "") or ""
        if not body:
            continue
        new_body, merges = process_page(body)
        if merges:
            e["body"] = new_body
            pages_changed += 1
            total_merges += merges
            per_page.append((e.get("source_key"), merges))
    with POST_JSON.open("w", encoding="utf-8") as f:
        json.dump(data, f, ensure_ascii=False, indent=2)
    print(f"[done] {pages_changed} pages updated, {total_merges} heading-only sections merged\n")
    for sk, m in per_page:
        print(f"  merges={m}  {sk}")
    return 0


if __name__ == "__main__":
    sys.exit(main(sys.argv[1:]))
