"""Scrape kaindl.com reference case studies → references.en.json.

Reads the slug, listing title, and category map in `reference_index.json` (produced by walking
Load-more on https://www.kaindl.com/en/company/references/ via the chrome-devtools
MCP), fetches every detail page, and emits a ready-to-import references.en.json
at web/modules/custom/kaindl_references/data/references.en.json. Image bytes
land under scripts/catalog/image-import/page-bodies/company--references--<slug>/
and scripts/catalog/image-import/page-headers/company--references--<slug>/;
manifest rows are appended to the shared CSVs so `drush kpi-body-images` copies
them into public://.

Idempotent: reruns skip already-downloaded bytes and append only new manifest
rows. To refresh the slug/category list after kaindl.com adds or removes
references, re-run the chrome-devtools walk and regenerate reference_index.json.

Usage:
    python scripts/references/build_reference_seeds.py

Requires: beautifulsoup4 (bs4), Pillow (PIL) for image dimension probe.
"""

from __future__ import annotations

import csv
import hashlib
import json
import re
import sys
import urllib.error
import urllib.parse
import urllib.request
from dataclasses import dataclass, field
from pathlib import Path
from typing import Any

try:
    from bs4 import BeautifulSoup, Tag
except ImportError:  # pragma: no cover
    sys.stderr.write("This script requires beautifulsoup4. Install with: pip install beautifulsoup4\n")
    sys.exit(1)

try:
    from PIL import Image
except ImportError:  # pragma: no cover
    Image = None  # type: ignore

# Import the project transforms so scraped bodies match the kaindl_pages shape.
PROJECT_ROOT = Path(__file__).resolve().parents[2]
sys.path.insert(0, str(PROJECT_ROOT))
sys.path.insert(0, str(PROJECT_ROOT / "scripts"))
from scripts.pages.transforms import upgrade_rich_bullet_list, upgrade_text_image  # type: ignore  # noqa: E402
from scripts.pages.transforms import TransformContext  # type: ignore  # noqa: E402

SCRIPT_DIR = Path(__file__).resolve().parent
INDEX_FILE = SCRIPT_DIR / "reference_index.json"

IMAGE_WORKSPACE = PROJECT_ROOT / "scripts" / "catalog" / "image-import"
BODY_MANIFEST = IMAGE_WORKSPACE / "page_body_images_manifest.csv"
HEADER_MANIFEST = IMAGE_WORKSPACE / "page_header_images_manifest.csv"
PAGE_BODIES_DIR = IMAGE_WORKSPACE / "page-bodies"
PAGE_HEADERS_DIR = IMAGE_WORKSPACE / "page-headers"

REFERENCES_DATA_PATH = PROJECT_ROOT / "web" / "modules" / "custom" / "kaindl_references" / "data" / "references.en.json"
TEASER_TITLE_FIXES_PATH = PROJECT_ROOT / "web" / "modules" / "custom" / "kaindl_references" / "data" / "references.en.teaser-title-fixes.json"

USER_AGENT = "Mozilla/5.0 (compatible; kaindl-references-scraper/1.0)"
KAINDL_ORIGIN = "https://www.kaindl.com"


@dataclass
class BodyImage:
    url: str
    local_rel: str  # relative to IMAGE_WORKSPACE
    public_uri: str
    alt: str = ""
    width: int = 0
    height: int = 0


@dataclass
class ScrapedReference:
    slug: str
    source_key: str
    alias: str
    title: str
    teaser_title: str = ''
    kicker: str = ""
    intro: str = ""
    body: str = ""
    categories: list[str] = field(default_factory=list)
    sort_weight: int = 0
    teaser_image: dict[str, str] | None = None
    header_images: list[dict[str, Any]] = field(default_factory=list)
    used_products: list[dict[str, str]] = field(default_factory=list)


def http_get(url: str) -> bytes:
    req = urllib.request.Request(url, headers={"User-Agent": USER_AGENT})
    with urllib.request.urlopen(req, timeout=30) as resp:
        return resp.read()


def resolve_url(src: str) -> str:
    if src.startswith(("http://", "https://")):
        return src
    if src.startswith("//"):
        return "https:" + src
    return KAINDL_ORIGIN + ("" if src.startswith("/") else "/") + src


def _attr_str(value: object) -> str:
    if isinstance(value, str):
        return value
    if isinstance(value, list):
        return " ".join(str(part) for part in value)
    return "" if value is None else str(value)


def pick_highest_srcset(srcset: str) -> str:
    """Given `url1 345w, url2 640w, url3 960w` return the URL with the highest width."""
    parts = []
    for chunk in srcset.split(","):
        chunk = chunk.strip()
        if not chunk:
            continue
        m = re.match(r"(\S+)\s+(\d+)w", chunk)
        if m:
            parts.append((int(m.group(2)), m.group(1)))
        else:
            parts.append((0, chunk.split()[0]))
    if not parts:
        return ""
    parts.sort(key=lambda p: p[0], reverse=True)
    return parts[0][1]


def best_image_url(img_or_picture: Tag) -> str:
    """Prefer the last <source srcset=...> (desktop) at the highest width."""
    sources = img_or_picture.find_all("source") if img_or_picture.name == "picture" else []
    if not sources and img_or_picture.name == "img":
        parent = img_or_picture.parent
        if isinstance(parent, Tag) and parent.name == "picture":
            sources = parent.find_all("source")
    # Walk desktop→mobile (typically last source is desktop).
    for source in reversed(sources):
        if not isinstance(source, Tag):
            continue
        srcset = _attr_str(source.get("srcset"))
        if not srcset or srcset.startswith("data:image"):
            srcset = _attr_str(source.get("data-srcset"))
        if not srcset or srcset.startswith("data:image"):
            continue
        url = pick_highest_srcset(srcset)
        if url:
            return resolve_url(url)
    # Fallback to bare <img src>. Lazy-loaded Kaindl images often keep a
    # placeholder GIF in src and the real URL in data-src.
    if img_or_picture.name == "img":
        src = _attr_str(img_or_picture.get("src"))
        if not src or src.startswith("data:image"):
            src = _attr_str(img_or_picture.get("data-src"))
        if src and not src.startswith("data:image"):
            return resolve_url(src)
    inner_img = img_or_picture.find("img")
    if isinstance(inner_img, Tag):
        src = _attr_str(inner_img.get("src"))
        if not src or src.startswith("data:image"):
            src = _attr_str(inner_img.get("data-src"))
        if src and not src.startswith("data:image"):
            return resolve_url(src)
    return ""


def sha16(payload: bytes) -> str:
    return hashlib.sha1(payload).hexdigest()[:16]


def probe_dimensions(path: Path) -> tuple[int, int]:
    if Image is None:
        return 0, 0
    try:
        with Image.open(path) as im:
            return im.size
    except Exception:  # noqa: BLE001
        return 0, 0


def download_image(
    url: str,
    slug: str,
    kind: str = "body",
    image_index: int = 1,
    alt: str = "",
) -> BodyImage | None:
    """Download url to page-bodies/<slug>/<sha>.ext and return BodyImage."""
    if not url or url.startswith("data:image"):
        return None
    try:
        data = http_get(url)
    except (urllib.error.URLError, urllib.error.HTTPError) as exc:
        sys.stderr.write(f"  ! download failed for {url}: {exc}\n")
        return None

    ext = Path(urllib.parse.urlparse(url).path).suffix.lower() or ".jpg"
    if ext == ".jpe":
        ext = ".jpg"

    sha = sha16(data)
    slug_dir_name = f"company--references--{slug}"
    if kind == "header":
        target_dir = PAGE_HEADERS_DIR / slug_dir_name
        filename = "hero" if image_index == 1 else f"hero-{image_index}"
        target = target_dir / (filename + ext)
    else:
        target_dir = PAGE_BODIES_DIR / slug_dir_name
        target = target_dir / (sha + ext)

    target_dir.mkdir(parents=True, exist_ok=True)
    target.write_bytes(data)
    w, h = probe_dimensions(target)

    rel = target.relative_to(IMAGE_WORKSPACE).as_posix()
    public_uri = f"public://kaindl-pages/{'page-headers' if kind == 'header' else 'page-bodies'}/{slug_dir_name}/{target.name}"

    return BodyImage(
        url=url,
        local_rel=rel,
        public_uri=public_uri,
        alt=alt,
        width=w,
        height=h,
    )


def extract_header_block(soup: BeautifulSoup) -> tuple[str, str, str, list[dict[str, str]]]:
    """Return the header text and ordered caption-slider image metadata.

    The kaindl.com reference pages wrap their header inside
    `<section class="header-image content-element">` with two <h1>/<h2>s and a
    `.formatted-text` intro.
    """
    header = soup.select_one("section.header-image, .header-image")
    if not header:
        return "", "", "", []

    title = ""
    kicker = ""
    headings = header.find_all(["h1", "h2"])
    if headings:
        title = headings[0].get_text(strip=True)
    if len(headings) > 1:
        kicker = headings[1].get_text(strip=True)

    intro_block = header.select_one(".formatted-text")
    intro_html = intro_block.decode_contents().strip() if intro_block else ""

    labels: dict[int, str] = {}
    for label in header.select(".caption-slider__title[data-index]"):
        try:
            index = int(_attr_str(label.get("data-index")))
        except ValueError:
            continue
        labels[index] = re.sub(r"\s+", " ", label.get_text(" ", strip=True)).strip()

    slides: list[dict[str, str]] = []
    slide_elements = header.select(".header-image__basic-slider .basic-slider__item")
    if not slide_elements:
        fallback = header.find("picture") or header.find("img")
        slide_elements = [fallback] if isinstance(fallback, Tag) else []

    for index, slide in enumerate(slide_elements):
        picture = slide if slide.name in {"picture", "img"} else slide.find("picture") or slide.find("img")
        if not isinstance(picture, Tag):
            continue
        image_url = best_image_url(picture)
        if not image_url:
            continue
        img = picture if picture.name == "img" else picture.find("img")
        alt = _attr_str(img.get("alt")) if isinstance(img, Tag) else ""
        slides.append({
            "url": image_url,
            "label": labels.get(index, ""),
            "alt": alt.strip(),
        })

    return title, kicker, intro_html, slides


def normalize_used_products(body_root: BeautifulSoup) -> list[dict[str, str]]:
    """Extract Kaindl's mixed used-product modules into structured seed data."""
    used_products: list[dict[str, str]] = []

    def clean_text(value: str) -> str:
        return re.sub(r"\s+", " ", value).strip()

    def clone_img(img: Tag | None) -> Tag | None:
        if not isinstance(img, Tag):
            return None
        new_img = body_root.new_tag("img")
        for attr in ["src", "alt", "decoding", "loading"]:
            if img.get(attr):
                new_img[attr] = img[attr]
        new_img["class"] = "references-products__image"
        if not new_img.get("decoding"):
            new_img["decoding"] = "async"
        if not new_img.get("loading"):
            new_img["loading"] = "lazy"
        return new_img

    def split_code_name(text: str) -> tuple[str, str]:
        text = clean_text(text)
        match = re.match(r"^([A-Z0-9]{1,6}(?:\s+[A-Z0-9]{1,6}){0,2})\s+(.+)$", text)
        if match:
            return match.group(1), match.group(2)
        return "", text

    def make_card(title: str, img: Tag | None, href: str = "", code: str = "") -> Tag | None:
        title = clean_text(title)
        code = clean_text(code)
        if code and not title:
            title = code
            code = ""
        image = clone_img(img)
        if not title and image is None:
            return None
        card = body_root.new_tag("a" if href else "div", **{"class": "references-products__item"})
        if href:
            card["href"] = href
        if image is not None:
            figure = body_root.new_tag("figure", **{"class": "references-products__media"})
            figure.append(image)
            card.append(figure)
        meta = body_root.new_tag("span", **{"class": "references-products__meta"})
        if code:
            strong = body_root.new_tag("strong", **{"class": "references-products__code"})
            strong.string = code
            meta.append(strong)
        name = body_root.new_tag("span", **{"class": "references-products__name"})
        name.string = title
        meta.append(name)
        card.append(meta)
        return card

    def collect_card(card: Tag) -> None:
        image = card.find("img")
        code_el = card.find(class_="references-products__code")
        name_el = card.find(class_="references-products__name")
        code = clean_text(code_el.get_text(" ") if isinstance(code_el, Tag) else "")
        name = clean_text(name_el.get_text(" ") if isinstance(name_el, Tag) else card.get_text(" "))
        if code and name.startswith(code):
            name = clean_text(name[len(code):])
        href = clean_text(str(card.get("href") or ""))
        item = {
            "href": href,
            "code": code,
            "title": name,
            "image": clean_text(str(image.get("src") or "")) if isinstance(image, Tag) else "",
            "alt": clean_text(str(image.get("alt") or "")) if isinstance(image, Tag) else "",
        }
        if item not in used_products:
            used_products.append(item)

    used_headings = [
        h for h in body_root.find_all(["h2", "h3"])
        if "used product" in clean_text(h.get_text(" ")).lower()
    ]
    for heading in used_headings:
        section = heading.find_parent("section", class_="page-body__section")
        if not isinstance(section, Tag) or section.find(class_="references-products__grid"):
            continue

        cards: list[Tag] = []
        for item in section.select(".references-products__item"):
            strong = item.find("strong")
            code = clean_text(strong.get_text(" ")) if isinstance(strong, Tag) else ""
            title = clean_text(item.get_text(" "))
            if code and title.startswith(code):
                title = clean_text(title[len(code):])
            elif not code:
                code, title = split_code_name(title)
            image = item.find("img")
            card = make_card(title, image if isinstance(image, Tag) else None, _attr_str(item.get("href")), code)
            if card is not None:
                cards.append(card)

        if not cards and section.select(".content-carousel__slider-item"):
            imgs: list[Tag | None] = []
            for slide in section.select(".content-carousel__slider-item"):
                image = slide.find("img")
                imgs.append(image if isinstance(image, Tag) else None)
            labels = section.select(".content-carousel__labels-item")
            for idx, label in enumerate(labels):
                heading_el = label.find(["h3", "h4"])
                title = clean_text(heading_el.get_text(" ") if isinstance(heading_el, Tag) else label.get_text(" "))
                link = label.find("a", href=True)
                code, name = split_code_name(title)
                card = make_card(name, imgs[idx] if idx < len(imgs) else None, _attr_str(link.get("href")) if isinstance(link, Tag) else "", code)
                if card is not None:
                    cards.append(card)

        if not cards and section.find(class_="text-image-content__headline"):
            text_block = section.find(class_="formatted-text")
            title = clean_text(text_block.get_text(" ") if isinstance(text_block, Tag) else "")
            image = section.find("img")
            card = make_card(title, image if isinstance(image, Tag) else None)
            if card is not None:
                cards.append(card)

        if cards:
            for card in cards:
                collect_card(card)
            section.decompose()
        elif "used product" in clean_text(heading.get_text(" ")).lower():
            section.decompose()

    for section in list(body_root.select("section.page-body__section")):
        if section.find(class_="references-products__grid") or not section.select(".references-products__item"):
            continue
        heading = section.find(["h2", "h3"])
        heading_text = clean_text(heading.get_text(" ") if isinstance(heading, Tag) else "Used products")
        cards = []
        for item in section.select(".references-products__item"):
            strong = item.find("strong")
            code = clean_text(strong.get_text(" ")) if isinstance(strong, Tag) else ""
            title = clean_text(item.get_text(" "))
            if code and title.startswith(code):
                title = clean_text(title[len(code):])
            elif not code:
                code, title = split_code_name(title)
            image = item.find("img")
            card = make_card(title, image if isinstance(image, Tag) else None, _attr_str(item.get("href")), code)
            if card is not None:
                cards.append(card)
        if cards:
            for card in cards:
                collect_card(card)
            section.decompose()

    return used_products


def extract_and_download_body(soup: BeautifulSoup, slug: str) -> tuple[str, list[BodyImage], list[dict[str, str]]]:
    """Extract the main reference body (rich-bullet-list + text-image-content)
    and rewrite image URLs to public:// paths, downloading bytes along the way.

    Returns the body HTML (to be further transformed) plus the list of images
    downloaded.
    """
    # Reference detail pages use content-element blocks inside <main>; the
    # header-image block is handled separately. Pull all other content-elements.
    sections = []
    for el in soup.select(".content-element"):
        classes = set((el.get("class") or []))
        if "header-image" in classes:
            continue
        sections.append(el)

    if not sections:
        return "", [], []

    body_root = BeautifulSoup('<article class="page-body"></article>', "html.parser")
    article = body_root.article
    if not isinstance(article, Tag):
        raise RuntimeError("Could not create reference body article wrapper.")

    images: list[BodyImage] = []

    for section_el in sections:
        # Clone into a new <section> wrapper with our project's class.
        wrapper = body_root.new_tag("section", **{"class": "page-body__section section-spacer"})

        # Download any images in the section, rewriting <picture>/<img> to a
        # single <img src="public://..."/> pointing at the downloaded file.
        for picture in list(section_el.find_all("picture")):
            best = best_image_url(picture)
            if best:
                img_entity = download_image(best, slug, kind="body")
                if img_entity:
                    images.append(img_entity)
                    alt = picture.find("img", alt=True)
                    alt_text = _attr_str(alt.get("alt")) if isinstance(alt, Tag) else ""
                    img_entity.alt = alt_text
                    new_img = body_root.new_tag(
                        "img",
                        **{
                            "alt": alt_text,
                            "class": "",
                            "decoding": "async",
                            "loading": "lazy",
                            "src": img_entity.public_uri,
                        },
                    )
                    picture.replace_with(new_img)

        for img in list(section_el.find_all("img")):
            src = _attr_str(img.get("src"))
            if not src or src.startswith("data:image"):
                src = _attr_str(img.get("data-src"))
            if not src or src.startswith("data:image") or src.startswith("public://"):
                continue
            best = resolve_url(src)
            img_entity = download_image(best, slug, kind="body")
            if img_entity:
                images.append(img_entity)
                img_entity.alt = _attr_str(img.get("alt"))
                img.attrs = {
                    "alt": _attr_str(img.get("alt")),
                    "decoding": "async",
                    "loading": "lazy",
                    "src": img_entity.public_uri,
                }

        # Strip href=javascript:; and inline scripts.
        for a in section_el.find_all("a", href=lambda v: isinstance(v, str) and v.startswith("javascript:")):
            a.unwrap()
        for a in section_el.find_all("a", href=True):
            href = str(a["href"])
            if href.startswith(KAINDL_ORIGIN + "/"):
                a["href"] = urllib.parse.urlparse(href).path
        for script in section_el.find_all("script"):
            script.decompose()

        wrapper.append(section_el)
        article.append(wrapper)

    # Hand the resulting markup to the existing project transforms to produce
    # `.page-body__feature-list` + `.page-body__two-col` primitives. They
    # mutate the soup in-place given a TransformContext.
    ctx = TransformContext(
        source_key=f"/en/company/references/{slug}/",
        alias=f"/company/references/{slug}/",
        title=slug,
        slug=slug,
    )
    try:
        upgrade_rich_bullet_list.transform(body_root, ctx)
    except Exception as exc:  # noqa: BLE001
        sys.stderr.write(f"  ! upgrade_rich_bullet_list failed for {slug}: {exc}\n")
    try:
        upgrade_text_image.transform(body_root, ctx)
    except Exception as exc:  # noqa: BLE001
        sys.stderr.write(f"  ! upgrade_text_image failed for {slug}: {exc}\n")

    used_products = normalize_used_products(body_root)

    return str(body_root), images, used_products


def extract_category_labels(index_entry: dict[str, Any]) -> list[str]:
    cats = index_entry.get("categories") or []
    return [c for c in cats if isinstance(c, str) and c]


def append_manifest_rows(
    body_images: list[BodyImage],
    header_images: list[BodyImage],
    source_key: str,
    slug: str,
) -> None:
    """Append to page_body_images_manifest.csv and page_header_images_manifest.csv.
    Idempotent: rows with (source_key, local_path) already present are skipped.
    """
    # Body manifest.
    if body_images:
        existing: set[tuple[str, str]] = set()
        if BODY_MANIFEST.exists():
            with BODY_MANIFEST.open("r", encoding="utf-8", newline="") as f:
                reader = csv.reader(f)
                for i, row in enumerate(reader):
                    if i == 0:
                        continue
                    if len(row) >= 3:
                        existing.add((row[0], row[2]))
        with BODY_MANIFEST.open("a", encoding="utf-8", newline="") as f:
            writer = csv.writer(f, quoting=csv.QUOTE_MINIMAL)
            for img in body_images:
                if (source_key, img.local_rel) in existing:
                    continue
                writer.writerow([source_key, img.url, img.local_rel, img.public_uri, img.alt, str(img.width or ""), str(img.height or "")])
                existing.add((source_key, img.local_rel))

    # Header manifest.
    if header_images:
        existing_h: set[tuple[str, str]] = set()
        if HEADER_MANIFEST.exists():
            with HEADER_MANIFEST.open("r", encoding="utf-8", newline="") as f:
                reader = csv.reader(f)
                for i, row in enumerate(reader):
                    if i == 0:
                        continue
                    if len(row) >= 4:
                        existing_h.add((row[0], row[3]))
        with HEADER_MANIFEST.open("a", encoding="utf-8", newline="") as f:
            writer = csv.writer(f, quoting=csv.QUOTE_MINIMAL)
            key = f"company--references--{slug}"
            for image_index, image in enumerate(header_images, start=1):
                image_path = image.local_rel
                if (source_key, image_path) in existing_h:
                    continue
                writer.writerow([source_key, key, str(image_index), image_path])
                existing_h.add((source_key, image_path))


def scrape_one(index_entry: dict[str, Any]) -> ScrapedReference | None:
    slug = index_entry["slug"]
    source_key = index_entry["source_key"]
    alias = index_entry["alias"]
    url = f"{KAINDL_ORIGIN}{source_key}"

    sys.stderr.write(f"scraping {url}\n")
    try:
        raw = http_get(url)
    except (urllib.error.URLError, urllib.error.HTTPError) as exc:
        sys.stderr.write(f"  ! fetch failed: {exc}\n")
        return None

    soup = BeautifulSoup(raw, "html.parser")
    title, kicker, intro_html, header_slides = extract_header_block(soup)
    if not title:
        sys.stderr.write(f"  ! no title extracted, skipping\n")
        return None

    body_html, body_images, used_products = extract_and_download_body(soup, slug)

    downloaded_headers: list[tuple[BodyImage, dict[str, str]]] = []
    for image_index, slide in enumerate(header_slides, start=1):
        downloaded = download_image(
            slide["url"],
            slug,
            kind="header",
            image_index=image_index,
            alt=slide.get("alt", ""),
        )
        if downloaded is not None:
            downloaded_headers.append((downloaded, slide))

    # Use the hero (the detail page's header image) as the teaser card image.
    # kaindl.com's index teaser is a different crop of the same hero; we don't
    # re-fetch it. First body image is unreliable — it's often a project-info
    # icon or a used-products thumbnail, not a representative cover.
    teaser_info = None
    if downloaded_headers:
        teaser_info = {
            "public_uri": downloaded_headers[0][0].public_uri,
            "alt": title,
        }

    ref = ScrapedReference(
        slug=slug,
        source_key=source_key,
        alias=alias,
        title=title,
        teaser_title=str(index_entry.get('teaser_title') or title).strip(),
        kicker=kicker,
        intro=intro_html,
        body=body_html,
        categories=extract_category_labels(index_entry),
        sort_weight=int(index_entry.get("sort_weight") or 0),
        teaser_image=teaser_info,
        header_images=[
            {
                "image_path": image.local_rel,
                "dir_name": f"company--references--{slug}",
                "image_index": image_index,
                "label": slide.get("label", ""),
                "alt": image.alt,
            }
            for image_index, (image, slide) in enumerate(downloaded_headers, start=1)
        ],
        used_products=used_products,
    )
    append_manifest_rows(
        body_images,
        [image for image, _slide in downloaded_headers],
        source_key,
        slug,
    )
    return ref


def main() -> None:
    import argparse
    parser = argparse.ArgumentParser(description="Scrape kaindl.com reference detail pages.")
    parser.add_argument(
        "--allow-partial",
        action="store_true",
        help="Write references.en.json even if some slugs fail to scrape. Without this flag, "
             "any scrape failure aborts with a nonzero exit code so the importer never sees a "
             "partial seed (which would unpublish live references via unpublishMissingReferences).",
    )
    args = parser.parse_args()

    if not INDEX_FILE.exists():
        sys.stderr.write(f"missing index file: {INDEX_FILE}\n")
        sys.exit(1)
    index = json.loads(INDEX_FILE.read_text(encoding="utf-8"))
    entries = index.get("entries") or []
    if TEASER_TITLE_FIXES_PATH.exists():
        title_data = json.loads(TEASER_TITLE_FIXES_PATH.read_text(encoding='utf-8'))
        listing_titles = {
            row.get('source_key'): (row.get('teaser_title') or {}).get('value')
            for row in title_data.get('references') or []
        }
        for entry in entries:
            entry['teaser_title'] = listing_titles.get(entry.get('source_key')) or entry.get('teaser_title')

    # Load the previous seed (if any) so we can preserve entries for slugs the
    # scraper fails to refresh this run. Unpublishing a live reference because
    # a single HTTP request timed out is not acceptable.
    previous_by_key: dict[str, dict[str, Any]] = {}
    if REFERENCES_DATA_PATH.exists():
        try:
            prev_data = json.loads(REFERENCES_DATA_PATH.read_text(encoding="utf-8"))
            for r in prev_data.get("references") or []:
                sk = str(r.get("source_key") or "")
                if sk:
                    previous_by_key[sk] = r
        except json.JSONDecodeError:
            previous_by_key = {}

    references = []
    failed_entries: list[dict[str, Any]] = []
    for idx, entry in enumerate(entries, 1):
        ref = scrape_one(entry)
        if ref is None:
            failed_entries.append(entry)
            previous = previous_by_key.get(entry.get("source_key") or "")
            if previous is not None:
                references.append(previous)
                sys.stderr.write(f"  [{idx}/{len(entries)}] {entry.get('slug')} — FAILED, preserved previous entry\n")
            else:
                sys.stderr.write(f"  [{idx}/{len(entries)}] {entry.get('slug')} — FAILED, no previous entry to preserve\n")
            continue
        references.append({
            "source_key": ref.source_key,
            "alias": ref.alias,
            "title": ref.title,
            # Listing copy is intentionally independent from the detail H1.
            "teaser_title": ref.teaser_title,
            "headline": ref.kicker or ref.title,
            "kicker": ref.kicker,
            "intro": ref.intro,
            "body": ref.body,
            "categories": ref.categories,
            "sort_weight": ref.sort_weight,
            "teaser_image": ref.teaser_image,
            "header_images": ref.header_images,
            "used_products": ref.used_products,
        })
        sys.stderr.write(f"  [{idx}/{len(entries)}] {ref.slug} — ok\n")

    if failed_entries and not args.allow_partial:
        sys.stderr.write(
            f"\n!!! {len(failed_entries)} scrape failures; refusing to write seed without --allow-partial.\n"
            "Re-run the scraper later or pass --allow-partial if the failed slugs are expected to be "
            "missing from kaindl.com.\n"
        )
        for e in failed_entries:
            sys.stderr.write(f"  - {e.get('slug')} ({e.get('source_key')})\n")
        sys.exit(2)

    REFERENCES_DATA_PATH.parent.mkdir(parents=True, exist_ok=True)
    REFERENCES_DATA_PATH.write_text(
        json.dumps({
            "generated_at": index.get("generated_at"),
            "source": index.get("source"),
            "total": len(references),
            "failed_slugs": [e.get("slug") for e in failed_entries],
            "references": references,
        }, ensure_ascii=False, indent=2) + "\n",
        encoding="utf-8",
    )
    sys.stderr.write(
        f"\nWrote {len(references)} references to {REFERENCES_DATA_PATH}\n"
        f"(failed scrapes: {len(failed_entries)})\n"
    )


if __name__ == "__main__":
    main()
