"""Recover intro paragraphs that leaked into body due to the single-<p>
capture bug in the old extract_header_fields rule.

Flow:
  1. For every page, read the pre-transform body.
  2. Locate the intro block (`.page-intro__text`, `.header-image__content`,
     `.page-intro`, etc.) and extract ALL its `<p>` elements as the true
     intro HTML.
  3. Normalize that true intro and compare to the current `header_intro`.
     If the true intro has MORE paragraphs than we currently store, replace
     header_intro with the full set and strip any of those paragraphs that
     still live in the first body section.

Idempotent: if current header_intro already contains every true-intro
paragraph, no change.
"""

from __future__ import annotations

import json
import re
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"
PRE_JSON = REPO_ROOT / "web" / "modules" / "custom" / "kaindl_pages" / "data" / "pages-content.en.pre-transform.json"

_INTRO_CLASS_RE = re.compile(r"(page-intro__text|header-image__content|\bpage-intro\b)")


def _norm(s: str) -> str:
    return re.sub(r"\s+", " ", re.sub(r"<[^>]+>", "", s or "")).strip().lower().rstrip(".!? ")


def _true_intro_paragraphs(pre_body: str) -> list[str]:
    """Return the list of <p> strings inside the intro block. Empty list
    if there is no identifiable intro block."""
    soup = BeautifulSoup(pre_body, "html.parser")
    header = soup.find(class_="header-image") or soup
    node = header.find(class_=_INTRO_CLASS_RE) if isinstance(header, Tag) else None
    if not isinstance(node, Tag):
        return []
    formatted = node.find(class_="formatted-text")
    source = formatted if isinstance(formatted, Tag) else node
    ps = source.find_all("p")
    out = []
    for p in ps:
        # Strip utility classes from the paragraph so it matches theme styling.
        for t in p.find_all(True):
            if t.attrs and "class" in t.attrs:
                kept = [c for c in t["class"] if not (c.startswith("color-") or c.startswith("ft")
                         or c in ("f-bold", "f-light", "upper"))]
                if kept:
                    t["class"] = kept
                else:
                    del t["class"]
        text_only = re.sub(r"<[^>]+>", "", str(p)).strip()
        if not text_only:
            continue
        # Re-serialize without attributes on <p> itself.
        p.attrs = {}
        out.append(str(p))
    return out


def process_page(post_entry: dict, pre_entry: dict) -> dict:
    report = {"intro_paragraphs_added": 0, "body_paragraphs_removed": 0}
    pre_body = pre_entry.get("body", "") or ""
    if not pre_body:
        return report
    true_paras = _true_intro_paragraphs(pre_body)
    if len(true_paras) <= 1:
        # Nothing to recover — the extraction captured everything (or there's
        # nothing to capture).
        return report
    current_intro = post_entry.get("header_intro", "") or ""
    current_norms = {_norm(str(p)) for p in BeautifulSoup(current_intro, "html.parser").find_all("p")}
    if not current_norms:
        current_norms = {_norm(current_intro)}
    true_norms = [_norm(p) for p in true_paras]
    missing = [i for i, n in enumerate(true_norms) if n and n not in current_norms]
    if not missing:
        return report

    # Replace header_intro with the full set of true paragraphs.
    post_entry["header_intro"] = "".join(true_paras)
    report["intro_paragraphs_added"] = len(missing)

    # Strip those paragraphs from the body's first section (if they leaked in).
    body_html = post_entry.get("body", "") or ""
    if not body_html:
        return report
    soup = BeautifulSoup(body_html, "html.parser")
    art = soup.find("article", class_="page-body")
    if not art:
        return report
    first_section = art.find("section", recursive=False)
    if not first_section:
        return report
    copy_div = first_section.find(class_="kaindl-copy")
    if not copy_div:
        return report
    true_norm_set = set(true_norms)
    for p in list(copy_div.find_all("p")):
        p_n = _norm(str(p))
        if p_n and p_n in true_norm_set:
            p.decompose()
            report["body_paragraphs_removed"] += 1
    # If the section is now empty, drop it.
    if not copy_div.get_text(strip=True) and not copy_div.find(["img", "iframe", "a"]):
        first_section.decompose()
    post_entry["body"] = str(soup)
    return report


def main(argv: Iterable[str] = ()) -> int:
    with POST_JSON.open(encoding="utf-8") as f:
        post = json.load(f)
    with PRE_JSON.open(encoding="utf-8") as f:
        pre = json.load(f)
    pre_list = pre["pages"] if "pages" in pre else pre
    pre_by_key = {(e.get("source_key") or "").rstrip("/"): e for e in pre_list}

    totals = {"pages_changed": 0, "paragraphs_added": 0, "body_paragraphs_removed": 0}
    per_page = []
    for entry in post["pages"]:
        sk = (entry.get("source_key") or "").rstrip("/")
        pre_entry = pre_by_key.get(sk)
        if not pre_entry:
            continue
        rep = process_page(entry, pre_entry)
        if rep["intro_paragraphs_added"]:
            totals["pages_changed"] += 1
            totals["paragraphs_added"] += rep["intro_paragraphs_added"]
            totals["body_paragraphs_removed"] += rep["body_paragraphs_removed"]
            per_page.append((sk, rep))

    with POST_JSON.open("w", encoding="utf-8") as f:
        json.dump(post, f, ensure_ascii=False, indent=2)
    print(f"[done] {totals['pages_changed']} pages updated; "
          f"+{totals['paragraphs_added']} intro paragraphs recovered, "
          f"-{totals['body_paragraphs_removed']} duplicate body paragraphs.\n")
    for sk, rep in per_page:
        print(f"  +p={rep['intro_paragraphs_added']}  -p={rep['body_paragraphs_removed']}  {sk}")
    return 0


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