"""Strip decorative junk left over from source-site markup:

  - Sections whose only meaningful content is a `<p>___...___</p>` separator
    (kaindl.com authors used underscore runs as horizontal dividers).
  - Empty kaindl-copy sections (`<p>&nbsp;</p>` or just whitespace).
  - Standalone image-only sections that follow another image/grid and look
    like orphan decorative artefacts (no heading, no body, no link).

Idempotent. Run across all 79 pages.
"""

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"

_HR_JUNK = re.compile(r"^[_\-=•·\s]+$")


def _is_hr_junk_paragraph(p: Tag) -> bool:
    text = p.get_text(" ", strip=True)
    return bool(text) and bool(_HR_JUNK.match(text))


def _section_is_empty_or_junk(sec: Tag) -> bool:
    # Has only kaindl-copy with junk paragraphs / no text?
    copy = sec.find(class_="kaindl-copy")
    if copy is None:
        return False
    # If there's any non-copy descendant that is meaningful, keep.
    if sec.find(class_=["page-body__two-col", "collection-teaser",
                         "page-body__feature-list", "page-body__feature-list-section",
                         "page-body__video", "page-body__teaser-banner",
                         "page-body__product-grid", "page-body__downloads",
                         "page-body__faq", "page-body__gallery"]):
        return False
    if sec.find("img"):
        return False
    # Check paragraph contents
    ps = copy.find_all("p")
    if not ps:
        # No p — might be just a heading? Preserve.
        return False
    all_junk = True
    for p in ps:
        if _is_hr_junk_paragraph(p):
            continue
        text = p.get_text(" ", strip=True)
        if not text:
            continue
        all_junk = False
        break
    # Also ensure there's no heading / link / strong with real content
    for t in copy.find_all(["h2", "h3", "h4", "a", "strong", "em", "ul", "ol"]):
        if t.get_text(" ", strip=True):
            all_junk = False
            break
    return all_junk


def main() -> int:
    with PAGES_JSON.open(encoding="utf-8") as f:
        data = json.load(f)

    removed_total = 0
    pages_changed = 0
    for e in data["pages"]:
        body = e.get("body", "") or ""
        if "page-body" not in body:
            continue
        soup = BeautifulSoup(body, "html.parser")
        art = soup.find("article", class_="page-body")
        if not art:
            continue
        removed = 0
        for sec in list(art.find_all("section", recursive=False)):
            if _section_is_empty_or_junk(sec):
                sec.decompose()
                removed += 1
        if removed:
            e["body"] = str(soup)
            pages_changed += 1
            removed_total += removed
    with PAGES_JSON.open("w", encoding="utf-8") as f:
        json.dump(data, f, ensure_ascii=False, indent=2)
    print(f"[done] stripped {removed_total} junk sections across {pages_changed} pages")
    return 0


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