"""Unwrap redundant inner `<section class="page-body__X-section">` wrappers
that live as the sole child of a `<section class="page-body__section">`.

The content upgraders (upgrade_downloads, upgrade_content_carousel,
upgrade_job_list, upgrade_rich_bullet_list) historically emitted a nested
inner section with their own BEM-prefixed name. Combined with the
final-pass `upgrade_sections` wrapper, every component ends up double-
wrapped:

    <section class="page-body__section">
      <section class="page-body__downloads-section">  ← redundant
        <h2>…</h2>
        <ul class="page-body__downloads">…</ul>
      </section>
    </section>

The inner wrapper adds no styling value (none of them carry CSS rules
that matter after the theme pass) and produces an extra, meaningless
`<section>` for screen readers. Unwrap it.

Covers four BEM class names: `__downloads-section`, `__gallery-section`,
`__faq-section`, `__feature-list-section`.

Idempotent.
"""

from __future__ import annotations

import json
import sys
from pathlib import Path

from bs4 import BeautifulSoup, Tag

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

REDUNDANT_WRAPPER_CLASSES = (
    "page-body__downloads-section",
    "page-body__gallery-section",
    "page-body__faq-section",
    "page-body__feature-list-section",
)


def process_body(body: str) -> tuple[str, int]:
    if not body or "page-body__section" not in body:
        return body, 0
    soup = BeautifulSoup(body, "html.parser")
    unwraps = 0
    for parent in soup.find_all("section", class_="page-body__section"):
        for child in list(parent.children):
            if not isinstance(child, Tag) or child.name != "section":
                continue
            classes = child.get("class") or []
            if any(c in REDUNDANT_WRAPPER_CLASSES for c in classes):
                child.unwrap()
                unwraps += 1
    if unwraps:
        return str(soup), unwraps
    return body, 0


def main() -> int:
    with POST_JSON.open(encoding="utf-8") as f:
        data = json.load(f)
    pages_changed = 0
    total = 0
    per_page = []
    for e in data["pages"]:
        body = e.get("body", "") or ""
        new_body, n = process_body(body)
        if n:
            e["body"] = new_body
            pages_changed += 1
            total += n
            per_page.append((e.get("source_key"), n))
    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} redundant wrappers unwrapped\n")
    for sk, n in per_page[:50]:
        print(f"  unwraps={n}  {sk}")
    return 0


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