"""Promote `.page-body__gallery` ULs out of `.kaindl-copy` wrappers so the
grid stretches to the full section width (the `.kaindl-copy` max-width
of 45rem was clipping gallery grids to half-screen).

Also merges consecutive sibling `<ul class="page-body__gallery">` elements
into one — the source sometimes emits two rows as separate ULs but they
share the same class + captioned variant, so they should form a single
unified grid.

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"


def merge_adjacent_galleries(section: Tag) -> int:
    """Merge consecutive `.page-body__gallery` ULs inside `section` into one."""
    merges = 0
    # Walk the tree; for each gallery ul, check if the next element sibling
    # is also a gallery ul with the same class set — if so, move its <li>s
    # into this one and decompose it.
    changed = True
    while changed:
        changed = False
        for ul in section.find_all("ul", class_="page-body__gallery"):
            nxt = ul.find_next_sibling()
            while nxt is not None and isinstance(nxt, Tag) is False:
                nxt = nxt.find_next_sibling()
            if isinstance(nxt, Tag) and nxt.name == "ul" and "page-body__gallery" in (nxt.get("class") or []):
                for li in list(nxt.find_all("li", recursive=False)):
                    ul.append(li.extract())
                nxt.decompose()
                merges += 1
                changed = True
                break
    return merges


def process_body(body: str) -> tuple[str, dict]:
    report = {"unwraps": 0, "merges": 0}
    if "page-body__gallery" not in body:
        return body, report
    soup = BeautifulSoup(body, "html.parser")
    article = soup.find("article", class_="page-body") or soup

    # Unwrap any .kaindl-copy whose only meaningful child is a gallery ul
    # (or whose children are all gallery-related).
    for copy in list(article.find_all(class_="kaindl-copy")):
        galleries = copy.find_all("ul", class_="page-body__gallery", recursive=False)
        # Also count other meaningful children (not whitespace, not empty).
        meaningful = [c for c in copy.children
                      if isinstance(c, Tag) and c.name not in (None,)]
        if galleries and len(galleries) == len(meaningful):
            copy.unwrap()
            report["unwraps"] += 1

    # Merge adjacent galleries inside each section.
    for sec in article.find_all("section", class_="page-body__section"):
        report["merges"] += merge_adjacent_galleries(sec)

    if report["unwraps"] or report["merges"]:
        return str(soup), report
    return body, report


def main() -> int:
    with POST_JSON.open(encoding="utf-8") as f:
        data = json.load(f)
    totals = {"pages_changed": 0, "unwraps": 0, "merges": 0}
    per_page = []
    for e in data["pages"]:
        body = e.get("body", "") or ""
        new_body, rep = process_body(body)
        if rep["unwraps"] or rep["merges"]:
            e["body"] = new_body
            totals["pages_changed"] += 1
            totals["unwraps"] += rep["unwraps"]
            totals["merges"] += rep["merges"]
            per_page.append((e.get("source_key"), rep))
    with POST_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['unwraps']} kaindl-copy unwraps, "
          f"{totals['merges']} adjacent-gallery merges\n")
    for sk, rep in per_page:
        print(f"  unwrap={rep['unwraps']} merge={rep['merges']}  {sk}")
    return 0


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