"""Swap `.page-body__two-col--photo` → `.page-body__two-col--portrait` on
sections whose image source is intrinsically small (<=400px wide).

Without this, small portrait headshots get upscaled to full-column width by
the `--photo` variant, producing visible blur (see /for-partners/trade-
industry/ with 29 x 320w headshots). The `--portrait` variant caps the figure
column at ~20rem so the image renders at native size.

Reads width from `scripts/catalog/image-import/page_body_images_manifest.csv`
(public_uri → width). Falls back to 'no match' (no change) when the body's
img src does not resolve against the manifest.

Idempotent: running twice produces the same result.
"""

from __future__ import annotations

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

THRESHOLD = 400  # pixels; below this the image won't scale well in --photo.


def load_manifest_width_map() -> dict[str, int]:
    out: dict[str, int] = {}
    with MANIFEST.open(encoding="utf-8", newline="") as f:
        for row in csv.DictReader(f):
            try:
                w = int(row.get("width") or 0)
            except ValueError:
                w = 0
            uri = row.get("public_uri", "").strip()
            if uri and w > 0:
                out[uri] = w
    return out


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

    changed_total = 0
    touched_pages = 0
    for e in data["pages"]:
        body = e.get("body", "") or ""
        if "--photo" not in body:
            continue
        soup = BeautifulSoup(body, "html.parser")
        page_changed = 0
        for div in soup.find_all("div", class_=lambda c: c and "page-body__two-col--photo" in c):
            fig = div.find("figure", class_="page-body__media")
            if not fig:
                continue
            img = fig.find("img")
            if not img:
                continue
            src = img.get("src", "")
            w = widths.get(src)
            if not w:
                continue
            if w > THRESHOLD:
                continue
            # Swap class.
            classes = [c for c in (div.get("class") or []) if c != "page-body__two-col--photo"]
            if "page-body__two-col--portrait" not in classes:
                classes.append("page-body__two-col--portrait")
            div["class"] = classes
            page_changed += 1
        if page_changed:
            e["body"] = str(soup)
            touched_pages += 1
            changed_total += page_changed

    with POST_JSON.open("w", encoding="utf-8") as f:
        json.dump(data, f, ensure_ascii=False, indent=2)
    print(f"[done] {changed_total} sections reclassified across {touched_pages} pages")
    return 0


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