#!/usr/bin/env python3
"""Modernize body HTML in pages-content.en.json for the kaindl_pages importer.

Usage (from repo root, with .venv active):
    python scripts/pages/transform_page_seeds.py --tier 1
    python scripts/pages/transform_page_seeds.py --only "/en/imprint/,/en/privacy/"
    python scripts/pages/transform_page_seeds.py --all --download-images

Outputs:
- web/modules/custom/kaindl_pages/data/pages-content.en.json (rewritten in place, adds header_kicker/header_intro)
- scripts/catalog/image-import/page_body_images_manifest.csv
- scripts/catalog/image-import/page-bodies/<slug>/<hash>.<ext> (when --download-images)
- scripts/pages/transform_report.json, icon_inventory.json, alt_text_review.json,
  header_extraction_log.json, title_mismatch.json

The pipeline is intentionally idempotent: running it twice on an already-modernized
JSON yields the same bytes out.
"""

from __future__ import annotations

import argparse
import json
import os
import re
import sys
from pathlib import Path

# When run as a script, ensure sibling package `transforms` and project-level
# helpers are importable.
_HERE = Path(__file__).resolve().parent
REPO_ROOT = _HERE.parents[1]
for path in (REPO_ROOT, _HERE):
    if str(path) not in sys.path:
        sys.path.insert(0, str(path))

from bs4 import BeautifulSoup, Tag  # noqa: E402

from transforms import (  # noqa: E402
    RULE_ORDER,
    TRANSFORM_VERSION,
    HeaderExtraction,
    TransformContext,
)

PAGES_JSON = REPO_ROOT / "web" / "modules" / "custom" / "kaindl_pages" / "data" / "pages-content.en.json"
PAGES_BASELINE = PAGES_JSON.with_name("pages-content.en.pre-transform.json")

SHARED_IMAGE_ROOT = REPO_ROOT / "scripts" / "catalog" / "image-import"
BODY_IMAGES_TREE = SHARED_IMAGE_ROOT / "page-bodies"
BODY_IMAGES_MANIFEST = SHARED_IMAGE_ROOT / "page_body_images_manifest.csv"

REPORT_DIR = REPO_ROOT / "scripts" / "pages"
REPORT_TRANSFORM = REPORT_DIR / "transform_report.json"
REPORT_ICONS = REPORT_DIR / "icon_inventory.json"
REPORT_ALT = REPORT_DIR / "alt_text_review.json"
REPORT_HEADER = REPORT_DIR / "header_extraction_log.json"
REPORT_TITLE = REPORT_DIR / "title_mismatch.json"

TITLE_OVERRIDES = {
    "/en/for-partners/": "Kaindl for Partners",
    "/en/careers/job-offers/": "Open positions at Kaindl",
    "/en/careers/apprenticeships-kaindl/": "Apprenticeships at Kaindl",
    "/en/careers/application/": "Your application to Kaindl",
}

DESCRIPTION_OVERRIDES = {
    "/en/careers/job-offers/": {
        "description": "Are you interested in a career at Kaindl? You can find all the open positions at our plants in Wals/Salzburg and Lungötz here. Simply submit your application via our career portal. We look forward to hearing from you!",
    },
    "/en/careers/apprenticeships-kaindl/": {
        "description": "Aim high – with an apprenticeship at Kaindl. Are you interested in an apprenticeship in a specific craft? Or perhaps in the field of technology or commerce? Would you like an apprenticeship with exciting and interesting tasks and friendly colleagues? Then Kaindl is the right place for you.",
    },
    "/en/careers/application/": {
        "description": "Get your dream job with the right application. Do you want to apply for a job at Kaindl? We'll show you what you should pay attention to in your application and what steps you will take during the application process.",
    },
}

# Tier buckets are source_key allowlists. Kept here (not in the plan) so the
# driver is the single source of truth the user runs.
TIERS: dict[int, list[str]] = {
    # Flat-prose legal pages. /sales-delivery/ moved to Tier 4 because it uses
    # the .product-detail__downloads-* pattern that needs upgrade_downloads.
    1: [
        "/en/imprint/",
        "/en/privacy/",
        "/en/legal-notice/",
        "/en/cookies/",
    ],
    # Reference pages. The /company/references/ hub page is intentionally
    # deferred to a later tier because it uses a different teaser-grid pattern.
    2: [
        "/en/company/references/11decks-community-spaces/",
        "/en/company/references/alpencamping-nenzing/",
        "/en/company/references/bafep-salzburg/",
        "/en/company/references/biohotel-sturm/",
        "/en/company/references/bsfz-kitzsteinhorn/",
        "/en/company/references/casino-richthofen/",
        "/en/company/references/columbus-travel-agency/",
        "/en/company/references/ent-center-lueneburg/",
        "/en/company/references/fo-guang-shan-temple-berlin/",
        "/en/company/references/formex-village/",
        "/en/company/references/gleiss-wohnarchitektur/",
        "/en/company/references/hotel-zur-kapelle/",
        "/en/company/references/kitchen-in-private-apartment/",
        "/en/company/references/pur-fit-altenmarkt/",
    ],
    # Company / careers / partners pages whose only structural pattern is the
    # text-image-content two-col grid (handled by upgrade_text_image). The
    # four pages that use content-carousel / testimonials-slider / job-list
    # are deferred to Tier 3b when those rules are implemented.
    3: [
        # /en/company/ (the hub) is deferred — it uses .collection-teasers
        # and a body-level .caption-slider wrapping a .basic-slider, neither
        # of which have real transforms yet. Picked up in a later tier.
        "/en/company/facts-and-figures/",
        "/en/company/floor-house/",
        "/en/company/history/",
        "/en/company/innovations/",
        "/en/company/references/",
        "/en/company/responsibility/",
        "/en/careers/",
        "/en/careers/application/",
        "/en/for-partners/",
        "/en/for-partners/architects-processors/",
        "/en/for-partners/architects-processors/architect-sales-support/",
        "/en/for-partners/architects-processors/architects-contact/",
        "/en/for-partners/architects-processors/contact/",
        "/en/for-partners/architects-processors/references/",
        "/en/for-partners/suppliers/",
        "/en/for-partners/suppliers/technical-purchases/",
        "/en/for-partners/suppliers/wood-procurement/",
        "/en/for-partners/trade-industry/",
        # Specialty pages handled by upgrade_job_list / upgrade_testimonials /
        # upgrade_content_carousel (added once those rules came online).
        "/en/careers/apprenticeships-kaindl/",
        "/en/careers/job-offers/",
        "/en/company/people-at-kaindl/",
        "/en/company/press-and-news/",
    ],
    # Downloads / service-knowledge / sales-delivery. Needs real
    # upgrade_downloads and upgrade_faq (for collapsible FAQs).
    4: [
        "/en/sales-delivery/",
        "/en/service-knowledge/antibacterial-surfaces/",
        "/en/service-knowledge/downloads/",
        "/en/service-knowledge/downloads/brochures/",
        "/en/service-knowledge/downloads/dop/",
        "/en/service-knowledge/downloads/factsheets/",
        "/en/service-knowledge/downloads/installation-instructions/",
        "/en/service-knowledge/downloads/technical-downloads-boards/",
        "/en/service-knowledge/downloads/technical-downloads-floors/",
        "/en/service-knowledge/downloads/tenderspecifications/",
        "/en/service-knowledge/downloads/ukca/",
        "/en/service-knowledge/events/",
        "/en/service-knowledge/faq/",
        "/en/service-knowledge/healthy-living/",
        "/en/service-knowledge/underfloor-heating/",
    ],
    # Landing pages + the /en/company/ hub (deferred from Tier 3 — shares the
    # same collection-teasers grid pattern).
    5: [
        "/en/company/",
        "/en/landingpages/aqua-pro/",
        "/en/landingpages/boards-collection-2020/",
        "/en/landingpages/boards-collection-2020/colourline/",
        "/en/landingpages/boards-collection-2020/concreteart/",
        "/en/landingpages/boards-collection-2020/fabricart/",
        "/en/landingpages/boards-collection-2020/metalart/",
        "/en/landingpages/boards-collection-2020/realwood/",
        "/en/landingpages/boards-collection-2020/stoneart/",
        "/en/landingpages/boards-collection-2020/woodline/",
        "/en/landingpages/boards-collection-lead-2022/",
        "/en/landingpages/endgrain/",
        "/en/landingpages/enterms/",
        "/en/landingpages/flooring-collection-2023/",
        "/en/landingpages/flooring-collection-2024/",
        "/en/landingpages/native-oak/",
        "/en/landingpages/oak-evoke/",
        "/en/landingpages/purchase/",
    ],
    # Outliers — bespoke marketing / product-focused pages that don't fit the
    # standard section/category patterns but reuse existing rules.
    6: [
        "/en/bathroom-panels/",
        "/en/boards-collection-2025/",
        "/en/boards/board-accessories/splashback/",
        "/en/entity/",
        "/en/flooring-collection-2025/",
        "/en/sustainability/",
    ],
}


def slug_from_source_key(source_key: str) -> str:
    """Match the slug convention used by scripts/catalog/image-import/page-headers/."""
    stripped = source_key.removeprefix("/en/").strip("/")
    return stripped.replace("/", "--") if stripped else "root"


def parse_args(argv: list[str] | None = None) -> argparse.Namespace:
    parser = argparse.ArgumentParser(description=__doc__)
    selection = parser.add_mutually_exclusive_group(required=True)
    selection.add_argument("--tier", type=int, choices=sorted(TIERS.keys()), help="Run a single tier.")
    selection.add_argument("--only", type=str, help="Comma-separated source_keys.")
    selection.add_argument("--all", action="store_true", help="Transform every page.")
    parser.add_argument("--download-images", action="store_true",
                        help="Download images referenced in transformed bodies into the shared image workspace.")
    parser.add_argument("--dry-run", action="store_true",
                        help="Run rules but do not write the JSON back.")
    return parser.parse_args(argv)


def select_source_keys(pages: list[dict], args: argparse.Namespace) -> set[str]:
    if args.tier is not None:
        return set(TIERS[args.tier])
    if args.only:
        return {k.strip() for k in args.only.split(",") if k.strip()}
    return {p["source_key"] for p in pages}


def load_pages() -> dict:
    return json.loads(PAGES_JSON.read_text(encoding="utf-8"))


def write_pages(data: dict) -> None:
    PAGES_JSON.write_text(
        json.dumps(data, indent=2, ensure_ascii=False) + "\n",
        encoding="utf-8",
    )


def transform_page(page: dict) -> tuple[TransformContext, BeautifulSoup]:
    # html.parser (stdlib) is used instead of lxml because lxml's HTML parser
    # mishandles HTML5 void elements like <source> and injects spurious closing
    # tags. html.parser is slower but correct; 79 pages is trivial either way.
    soup = BeautifulSoup(page.get("body", "") or "", "html.parser")
    ctx = TransformContext(
        source_key=page["source_key"],
        alias=page.get("alias", ""),
        title=page.get("title", ""),
        slug=slug_from_source_key(page["source_key"]),
    )
    # Seed any pre-existing header_kicker/header_intro so idempotent reruns preserve them.
    ctx.header = HeaderExtraction(
        kicker=(page.get("header_kicker") or ""),
        intro=(page.get("header_intro") or ""),
    )
    for name, rule in RULE_ORDER:
        # Fail closed — a rule crash aborts the batch so the JSON is never
        # partially rewritten. The user sees the full traceback and can fix
        # the offending rule before the next run.
        try:
            rule(soup, ctx)
        except Exception as exc:  # noqa: BLE001
            raise RuntimeError(
                f"Rule '{name}' failed on page {ctx.source_key}: {type(exc).__name__}: {exc}"
            ) from exc
    return ctx, soup


def serialize_body(soup: BeautifulSoup) -> str:
    # The lxml parser wraps any fragment in <html><body>. We want only the body
    # contents stored back in pages-content.en.json — never the outer shell.
    root = soup.find("article", class_="page-body")
    if isinstance(root, Tag):
        root["data-transformed"] = TRANSFORM_VERSION
    container = soup.body if soup.body else soup
    return container.decode_contents().strip()


def write_reports(results: list[TransformContext]) -> None:
    REPORT_DIR.mkdir(parents=True, exist_ok=True)
    transform_entries = [e for r in results for e in r.report_entries]
    REPORT_TRANSFORM.write_text(json.dumps(transform_entries, indent=2, ensure_ascii=False) + "\n", encoding="utf-8")

    icons = sorted({icon for r in results for icon in r.icon_ids})
    REPORT_ICONS.write_text(json.dumps(icons, indent=2, ensure_ascii=False) + "\n", encoding="utf-8")

    alt_entries = [e for r in results for e in r.alt_review]
    REPORT_ALT.write_text(json.dumps(alt_entries, indent=2, ensure_ascii=False) + "\n", encoding="utf-8")

    header_log = [
        {
            "source_key": r.source_key,
            "kicker": r.header.kicker,
            "intro_length": len(r.header.intro),
        }
        for r in results
    ]
    REPORT_HEADER.write_text(json.dumps(header_log, indent=2, ensure_ascii=False) + "\n", encoding="utf-8")

    title_entries = [
        {"source_key": r.source_key, **r.title_mismatch}
        for r in results
        if r.title_mismatch
    ]
    REPORT_TITLE.write_text(json.dumps(title_entries, indent=2, ensure_ascii=False) + "\n", encoding="utf-8")


MANIFEST_COLUMNS = ["source_key", "original_url", "local_path", "public_uri", "alt", "width", "height"]


def load_manifest() -> dict[str, dict[str, str]]:
    """Load the persisted manifest CSV keyed by public_uri. Empty if missing."""
    import csv

    if not BODY_IMAGES_MANIFEST.exists():
        return {}
    with BODY_IMAGES_MANIFEST.open("r", encoding="utf-8-sig", newline="") as fh:
        reader = csv.DictReader(fh)
        result = {}
        for row in reader:
            key = (row.get("public_uri") or "").strip()
            if not key:
                continue
            result[key] = {col: (row.get(col) or "").strip() for col in MANIFEST_COLUMNS}
        return result


def write_manifest(results: list[TransformContext], pages: list[dict]) -> dict[str, dict[str, str]]:
    """Merge in-memory rows from this run with the persisted CSV and rewrite it.

    Per-run idempotency: ``migrate_images`` skips images that are already under
    the ``public://`` namespace, so their manifest rows wouldn't be re-added
    this run. Without a merge, partial runs would slowly erode the CSV. The
    union keeps historical rows for tiers that aren't being re-transformed.
    New rows override existing ones (fresh alt text, dimensions, etc.).

    Orphan pruning: any row whose ``public_uri`` is not referenced by ANY page
    body in the current JSON is dropped. Otherwise ``kpi-body-images`` would
    import managed files no page uses, wasting disk + media table rows.

    Returns the merged dict keyed by public_uri so the caller can hand it to
    the download step without re-reading the CSV.
    """
    import csv

    SHARED_IMAGE_ROOT.mkdir(parents=True, exist_ok=True)
    merged = load_manifest()

    # Collect every public:// URI referenced in the current JSON. Used to
    # prune stale manifest rows that refer to images no page points at.
    referenced: set[str] = set()
    for page in pages:
        body = page.get("body") or ""
        if "public://" not in body:
            continue
        for m in re.finditer(r'public://[^\s"\'<>)]+', body):
            referenced.add(m.group(0))

    for ctx in results:
        for row in ctx.manifest_rows:
            key = row["public_uri"]
            existing = merged.get(key, {})
            updated = {col: existing.get(col, "") for col in MANIFEST_COLUMNS}
            for col in MANIFEST_COLUMNS:
                value = row.get(col) or existing.get(col) or ""
                updated[col] = str(value)
            merged[key] = updated

    # Prune orphans: drop any manifest row whose public_uri isn't referenced
    # by any page body in the current JSON. Only applies when the JSON actually
    # contains public:// URIs — otherwise the first run (before migrate_images
    # finishes) would wipe the manifest.
    if referenced:
        merged = {k: v for k, v in merged.items() if k in referenced}

    with BODY_IMAGES_MANIFEST.open("w", encoding="utf-8", newline="") as fh:
        writer = csv.DictWriter(fh, fieldnames=MANIFEST_COLUMNS)
        writer.writeheader()
        for key in sorted(merged.keys()):
            writer.writerow({col: merged[key].get(col, "") for col in MANIFEST_COLUMNS})

    return merged


def main(argv: list[str] | None = None) -> int:
    args = parse_args(argv)
    if not PAGES_BASELINE.exists():
        # Running without a baseline means parity verification can't fail-closed later.
        print(f"WARNING: baseline {PAGES_BASELINE.name} not found; snapshot current JSON before iterating further.",
              file=sys.stderr)

    data = load_pages()
    pages: list[dict] = data.get("pages", [])
    targets = select_source_keys(pages, args)

    results: list[TransformContext] = []
    for page in pages:
        if page["source_key"] not in targets:
            continue
        if page["source_key"] in TITLE_OVERRIDES:
            page["title"] = TITLE_OVERRIDES[page["source_key"]]
        if page["source_key"] in DESCRIPTION_OVERRIDES:
            page["description"] = DESCRIPTION_OVERRIDES[page["source_key"]]["description"]
        ctx, soup = transform_page(page)
        if not args.dry_run:
            page["body"] = serialize_body(soup)
            page["header_kicker"] = ctx.header.kicker
            page["header_intro"] = ctx.header.intro
            if page["source_key"] in DESCRIPTION_OVERRIDES:
                page["description"] = DESCRIPTION_OVERRIDES[page["source_key"]]["description"]
                page["header_kicker"] = ""
                page["header_intro"] = ""
        results.append(ctx)

    if not args.dry_run:
        write_pages(data)

    merged_manifest = write_manifest(results, pages)
    write_reports(results)

    print(f"transformed {len(results)} page(s); "
          f"manifest rows (fresh this run)={sum(len(r.manifest_rows) for r in results)}; "
          f"manifest rows (total on disk)={len(merged_manifest)}; "
          f"unknown patterns={sum(len(r.report_entries) for r in results)}")

    if args.download_images:
        summary = download_images(merged_manifest)
        print(
            f"download_images: total={summary['total']} "
            f"already_present={summary['already_present']} "
            f"downloaded={summary['downloaded']} "
            f"failed={summary['failed']} "
            f"missing_upstream={len(summary.get('missing_upstream', []))}"
        )

        # Clean up upstream 404s: drop manifest rows + unwrap <a href> in
        # bodies that point at the missing URIs. Not a deploy blocker — the
        # content is already broken on kaindl.com.
        if summary.get("missing_upstream"):
            print(
                f"  note: {len(summary['missing_upstream'])} URL(s) returned 404 on "
                "kaindl.com. Removing from manifest and unwrapping anchors in bodies.",
                file=sys.stderr,
            )
            for entry in summary["missing_upstream"][:5]:
                print(f"    UPSTREAM 404: {entry['url']}", file=sys.stderr)
            missing_uris = {e["public_uri"] for e in summary["missing_upstream"]}
            # Prune manifest.
            for uri in missing_uris:
                merged_manifest.pop(uri, None)
            # Rewrite bodies: unwrap <a href="<missing_uri>"> so inner text
            # survives as plain text. Load the JSON once, walk every page.
            data = load_pages()
            from bs4 import BeautifulSoup as _BS4
            dirty = False
            for page in data.get("pages", []):
                body = page.get("body") or ""
                if not any(uri in body for uri in missing_uris):
                    continue
                soup = _BS4(body, "html.parser")
                for a in list(soup.find_all("a", href=True)):
                    if a["href"].strip() in missing_uris:
                        a.unwrap()
                for img in list(soup.find_all("img", src=True)):
                    if img["src"].strip() in missing_uris:
                        img.decompose()
                page["body"] = (soup.body.decode_contents() if soup.body else soup.decode_contents()).strip()
                dirty = True
            if dirty:
                write_pages(data)

        if summary["failures"]:
            for failure in summary["failures"][:10]:
                print(f"  FAIL {failure['url']}: {failure['reason']}", file=sys.stderr)
            return 1
        # Rewrite manifest once dimensions have been filled in and orphans pruned.
        _flush_manifest_csv(merged_manifest)

    return 0


def _flush_manifest_csv(manifest: dict[str, dict[str, str]]) -> None:
    import csv

    SHARED_IMAGE_ROOT.mkdir(parents=True, exist_ok=True)
    with BODY_IMAGES_MANIFEST.open("w", encoding="utf-8", newline="") as fh:
        writer = csv.DictWriter(fh, fieldnames=MANIFEST_COLUMNS)
        writer.writeheader()
        for key in sorted(manifest.keys()):
            writer.writerow({col: manifest[key].get(col, "") for col in MANIFEST_COLUMNS})


def download_images(manifest: dict[str, dict[str, str]]) -> dict:
    """Fetch every manifest row whose local file is missing; fill width/height.

    Mutates the passed-in manifest dict in place — width/height columns are
    populated for every file with known dimensions (including already-present
    ones, so re-runs fill in what earlier partial runs missed).
    """
    import requests
    from PIL import Image

    SHARED_IMAGE_ROOT.mkdir(parents=True, exist_ok=True)

    failures: list[dict] = []
    missing_upstream: list[dict] = []
    downloaded = 0
    already_present = 0
    total = 0

    session = requests.Session()
    session.headers.update({"User-Agent": "KaindlPagesImageMigrator/1.0 (+https://kaindl.dev.creatizmo.com/)"})

    for public_uri, row in manifest.items():
        if not row.get("original_url") or not row.get("local_path"):
            continue
        total += 1
        local_full = SHARED_IMAGE_ROOT / row["local_path"].replace("/", os.sep)
        local_full.parent.mkdir(parents=True, exist_ok=True)

        if local_full.exists() and local_full.stat().st_size > 0:
            already_present += 1
        else:
            try:
                response = session.get(row["original_url"], timeout=30, stream=True)
                response.raise_for_status()
                with local_full.open("wb") as fh:
                    for chunk in response.iter_content(chunk_size=32 * 1024):
                        if chunk:
                            fh.write(chunk)
                if local_full.stat().st_size == 0:
                    local_full.unlink(missing_ok=True)
                    failures.append({"url": row["original_url"], "public_uri": public_uri, "reason": "empty response body"})
                    continue
                downloaded += 1
            except Exception as exc:  # noqa: BLE001
                entry = {"url": row["original_url"], "public_uri": public_uri, "reason": f"{type(exc).__name__}: {exc}"}
                # HTTP 404s against kaindl.com are upstream content issues —
                # segregate so the caller can auto-clean body references
                # without failing the whole batch.
                if "404" in entry["reason"] or "HTTPError" in entry["reason"]:
                    missing_upstream.append(entry)
                else:
                    failures.append(entry)
                continue

        # Non-image files (PDFs etc.) raise in Pillow; that's expected and
        # non-fatal — leave width/height empty.
        if not row.get("width") or not row.get("height"):
            try:
                with Image.open(local_full) as im:
                    row["width"] = str(im.width)
                    row["height"] = str(im.height)
            except Exception:  # noqa: BLE001
                pass

    return {
        "total": total,
        "already_present": already_present,
        "downloaded": downloaded,
        "failed": len(failures),
        "failures": failures,
        "missing_upstream": missing_upstream,
    }


if __name__ == "__main__":
    raise SystemExit(main())
