"""Rewrite the "Used products" block on every reference case study.

The Tier-2 merge mis-classified this block: kaindl.com renders a
`.references-products` grid with 3 product cards (each card: image + code +
decor name linked to the product page). In our post-transform body that
became 3 separate flat sections — our Tier-2 merge then fused the first card
into a `.collection-teaser` and left the remaining cards orphaned.

This script:
  1. Loads pre-transform JSON + post-transform JSON + body-image manifest.
  2. For every reference case-study page whose pre-transform body has
     `.references-products__item` cards:
       a. Extract card data from pre-transform (href, code, decor name, orig
          image URL).
       b. Map each orig URL → `public://` URI via the manifest
          (`original_url` column).
       c. Remove the Tier-2-induced `.collection-teaser` whose heading is
          "Used products" from post-transform body, plus any adjacent
          orphaned product-card sections matching the flat product-link
          shape.
       d. Append a new `.page-body__product-grid` section carrying all cards.
  3. Save post-transform JSON.

Idempotent: re-running won't double-insert — it first strips any existing
`.page-body__product-grid`, then re-emits.
"""

from __future__ import annotations

import csv
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"
MANIFEST = REPO_ROOT / "scripts" / "catalog" / "image-import" / "page_body_images_manifest.csv"


def load_manifest_url_map() -> dict[tuple[str, str], str]:
    """Map (source_key_normalized, original_url) → public_uri."""
    url_map: dict[tuple[str, str], str] = {}
    with MANIFEST.open(encoding="utf-8", newline="") as f:
        for row in csv.DictReader(f):
            key = (row["source_key"].rstrip("/"), row["original_url"])
            url_map[key] = row["public_uri"]
    return url_map


def _render_cards_ul(cards: list[dict]) -> str:
    items_html = ""
    for c in cards:
        items_html += (
            '<li class="page-body__product-grid__item">'
              f'<a class="page-body__product-grid__card" href="{c["href"]}">'
                '<figure class="page-body__product-grid__image">'
                  f'<img alt="{c.get("alt","")}" decoding="async" loading="lazy" src="{c["public_uri"]}"/>'
                '</figure>'
                f'<p class="page-body__product-grid__code">{c["code"]}</p>'
                f'<p class="page-body__product-grid__name">{c["name"]}</p>'
              '</a>'
            '</li>'
        )
    return f'<ul class="page-body__product-grid">{items_html}</ul>'


def build_grid_section(blocks: list[dict]) -> BeautifulSoup:
    """blocks: list of {heading: str, cards: [...]}.

    Single-block pages render as one section with <h2>heading</h2> + grid.
    Multi-block pages render one outer "Used products" h2 + one sub-section
    per block with <h3>subheading</h3> + grid.
    """
    if len(blocks) == 1:
        b = blocks[0]
        # Force the outer heading to "Used products" for editorial consistency
        # — individual block names (e.g. "Used products", product-line names)
        # all render under the same canonical label on kaindl.com.
        heading = b.get("heading") or "Used products"
        html = (
            '<section class="page-body__section section-spacer">'
              f'<h2>{heading}</h2>'
              f'{_render_cards_ul(b["cards"])}'
            '</section>'
        )
        return BeautifulSoup(html, "html.parser")

    sub_html = ""
    for b in blocks:
        sub_heading = b.get("heading") or "Products"
        sub_html += (
            '<div class="page-body__product-grid-group">'
              f'<h3>{sub_heading}</h3>'
              f'{_render_cards_ul(b["cards"])}'
            '</div>'
        )
    html = (
        '<section class="page-body__section section-spacer">'
          '<h2>Used products</h2>'
          f'<div class="page-body__product-grid-groups">{sub_html}</div>'
        '</section>'
    )
    return BeautifulSoup(html, "html.parser")


def extract_blocks_from_source(pre_body: str) -> list[dict]:
    """Return a list of {heading, cards[]} for every `.references-products`
    block on the page, preserving sub-groupings when kaindl.com uses them
    (e.g. formex-village has 'External walls', 'Roof', 'Internal walls',
    'Tree trunks')."""
    soup = BeautifulSoup(pre_body, "html.parser")
    blocks_out: list[dict] = []
    for block in soup.find_all(class_="references-products"):
        heading_el = (block.find(class_="references-products__headline")
                      or block.find(["h2", "h3"]))
        heading = heading_el.get_text(" ", strip=True) if heading_el else ""
        cards: list[dict] = []
        for card in block.find_all("a", class_="references-products__item"):
            href = card.get("href") or ""
            img = card.find("img")
            src = (img.get("data-src") or img.get("src") or "") if img else ""
            if src and not src.startswith("http"):
                src = "https://www.kaindl.com" + (src if src.startswith("/") else "/" + src)
            strong = card.find("strong")
            code = strong.get_text(" ", strip=True) if strong else ""
            text_div = card.find(class_="references-products__item-text")
            full_text = text_div.get_text(" ", strip=True) if text_div else ""
            name = full_text
            if code and full_text.startswith(code):
                name = full_text[len(code):].strip()
            alt = (img.get("title") or "") if img else ""
            cards.append({
                "href": href, "code": code, "name": name,
                "src": src, "alt": alt,
            })
        if cards:
            blocks_out.append({"heading": heading, "cards": cards})
    return blocks_out


_FLAT_PRODUCT_LINK_RE = re.compile(r"/boards/decor/details/|/boards/products/|/boards/decor/")


def _is_orphan_product_section(sec: Tag) -> bool:
    """Matches <section><a href="/en/boards/decor/details/..."><img/>
    <strong>CODE</strong> Name</a></section> — the flat remnants the Tier-2
    merge left behind on the reference pages."""
    if sec.find(class_=["page-body__two-col", "page-body__feature-list",
                         "page-body__feature-list-section", "collection-teaser",
                         "page-body__product-grid", "page-body__teaser-banner"]):
        return False
    a = sec.find("a", recursive=True)
    if not a:
        return False
    href = a.get("href") or ""
    if not _FLAT_PRODUCT_LINK_RE.search(href):
        return False
    # Must contain an img and a strong
    return bool(a.find("img") and a.find("strong"))


def process_page(source_key: str, post_body: str, pre_body: str,
                  url_map: dict[tuple[str, str], str]) -> tuple[str, dict]:
    report = {"cards_found": 0, "cards_mapped": 0, "teasers_removed": 0,
              "orphans_removed": 0, "grids_inserted": 0, "blocks": 0}
    blocks = extract_blocks_from_source(pre_body)
    total_cards = sum(len(b["cards"]) for b in blocks)
    report["cards_found"] = total_cards
    report["blocks"] = len(blocks)
    if not blocks:
        return post_body, report

    sk_norm = source_key.rstrip("/")
    resolved_blocks: list[dict] = []
    for b in blocks:
        resolved_cards = []
        for c in b["cards"]:
            public_uri = url_map.get((sk_norm, c["src"]))
            if not public_uri:
                continue
            resolved_cards.append({**c, "public_uri": public_uri})
        if resolved_cards:
            resolved_blocks.append({"heading": b["heading"], "cards": resolved_cards})

    mapped_cards = sum(len(b["cards"]) for b in resolved_blocks)
    report["cards_mapped"] = mapped_cards
    if mapped_cards != total_cards:
        # Missing some — skip to avoid partial/misleading grid.
        return post_body, report

    soup = BeautifulSoup(post_body, "html.parser")
    article = soup.find("article", class_="page-body")
    if not article:
        return post_body, report

    # Strip any existing product-grid section (idempotent re-run).
    for existing in article.select(".page-body__product-grid, .page-body__product-grid-groups"):
        sec = existing.find_parent("section", class_="page-body__section")
        if sec:
            sec.decompose()

    # Collect headings we need to purge from teasers / orphan sections.
    purge_headings = {"used products"}
    for b in blocks:
        if b["heading"]:
            purge_headings.add(b["heading"].strip().lower())

    # Remove collection-teasers whose headline matches any source block heading.
    for teaser in list(article.select(".collection-teaser")):
        headline = teaser.select_one(".collection-teaser__box-headline")
        if headline and headline.get_text(" ", strip=True).lower() in purge_headings:
            sec = teaser.find_parent("section", class_="page-body__section")
            if sec:
                sec.decompose()
                report["teasers_removed"] += 1

    # Remove any PLAIN sections whose h2/h3 matches a block heading.
    for h in list(article.find_all(["h2", "h3"])):
        if h.get_text(" ", strip=True).lower() in purge_headings:
            sec = h.find_parent("section", class_="page-body__section")
            if sec and not sec.find_parent(class_="page-body__product-grid"):
                sec.decompose()

    # Remove orphan flat-product-link sections left over from the merge pass.
    for sec in list(article.find_all("section", recursive=False)):
        if _is_orphan_product_section(sec):
            sec.decompose()
            report["orphans_removed"] += 1

    # Append the grid (single-heading or multi-heading depending on blocks).
    grid = build_grid_section(resolved_blocks)
    article.append(grid)
    report["grids_inserted"] += 1

    return str(soup), 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}
    url_map = load_manifest_url_map()

    touched = 0
    reports: list[tuple[str, dict]] = []

    for entry in post["pages"]:
        sk = (entry.get("source_key") or "").rstrip("/")
        if not sk.startswith("/en/company/references/") or sk == "/en/company/references":
            continue
        pre_entry = pre_by_key.get(sk)
        if not pre_entry:
            reports.append((sk, {"error": "no pre-transform body"}))
            continue
        new_body, rep = process_page(sk, entry.get("body", "") or "",
                                      pre_entry.get("body", "") or "", url_map)
        if new_body != entry.get("body"):
            entry["body"] = new_body
            touched += 1
        reports.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] {touched} pages updated\n")
    for sk, rep in reports:
        if rep.get("error"):
            print(f"  [ERR] {sk}: {rep['error']}")
        else:
            print(f"  cards={rep['cards_found']} mapped={rep['cards_mapped']} "
                  f"teasers_rm={rep['teasers_removed']} orphans_rm={rep['orphans_removed']} "
                  f"grids={rep['grids_inserted']}  {sk}")
    return 0


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