"""Rule 5: migrate body images and first-party media to public://.

Responsibilities:
- Collapse ``<picture>`` to a single ``<img>``.
- Rescue the real URL from ``data-src`` / ``data-srcset`` when ``src`` is a
  ``data:image/gif`` TYPO3 lazy placeholder.
- Strip lazy-load scaffolding (``data-src*``, ``data-sizes``, ``sizes``,
  ``srcset``, ``js-lazy``, ``image``, ``image--fluid`` classes).
- Default every ``<img>`` to ``loading="lazy"`` + ``decoding="async"``.
- For every remaining ``<img>`` whose src references kaindl.com content
  (``/fileadmin/…`` relative path or absolute https://www.kaindl.com/…):
    * compute a deterministic filename: ``sha1(absolute_url)[:16] + ext``,
    * append a manifest row to ``ctx.manifest_rows`` with
      ``original_url`` / ``local_path`` / ``public_uri`` / ``alt``,
    * rewrite the ``src`` attribute to the ``public://kaindl-pages/page-bodies/…`` URI.
- Images whose src cannot be resolved (data: placeholders with no data-src,
  unknown schemes) are logged to ``ctx.alt_review`` with a reason.

Width / height attributes are left empty by this rule; the driver's
``--download-images`` step probes downloaded files with Pillow and fills the
manifest columns before the CSV is written.

Idempotent: an ``<img>`` whose src already starts with
``public://kaindl-pages/page-bodies/`` is skipped on re-runs.
"""

from __future__ import annotations

import hashlib
import os
from pathlib import Path
from urllib.parse import unquote, urlparse

from bs4 import BeautifulSoup, Tag

from scripts.download_filenames import friendly_filename

from . import TransformContext

_LAZY_SRC_PREFIX = "data:image/gif"
_STRIP_ATTRS = ("data-src", "data-srcset", "data-sizes", "sizes", "srcset")
_STRIP_CLASSES = {"js-lazy", "image", "image--fluid", "lazy"}

_KAINDL_ORIGIN = "https://www.kaindl.com"
_PUBLIC_PREFIX = "public://kaindl-pages/page-bodies/"


def _attr_str(value: object) -> str:
    # BeautifulSoup attributes may be strings, token lists, or missing.
    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)


# Only absolute paths that start with these prefixes are migrated to public://.
# Everything else (about:blank, mailto:, relative without leading slash,
# external non-kaindl domains) is left alone.
_MIGRATABLE_PATH_PREFIXES = ("/fileadmin/", "/en/fileadmin/")


def transform(soup: BeautifulSoup, ctx: TransformContext) -> None:
    # 1. Collapse <picture> to its <img>.
    for pic in list(soup.find_all("picture")):
        if not isinstance(pic, Tag):
            continue
        img = pic.find("img")
        if not isinstance(img, Tag):
            pic.decompose()
            continue
        pic.replace_with(img)

    # 2. Normalize every <img>.
    for img in list(soup.find_all("img")):
        if not isinstance(img, Tag):
            continue
        _rescue_lazy_src(img)
        _strip_lazy_attrs(img)
        _strip_lazy_classes(img)
        img.attrs.setdefault("loading", "lazy")
        img.attrs.setdefault("decoding", "async")

        src = _attr_str(img.get("src")).strip()
        alt = _attr_str(img.get("alt")).strip()

        if not src:
            ctx.alt_review.append(
                {
                    "source_key": ctx.source_key,
                    "reason": "empty_src",
                    "src": src,
                    "alt": alt,
                }
            )
            continue

        if src.startswith(_PUBLIC_PREFIX):
            continue  # Already migrated — idempotent no-op.

        if src.startswith("data:"):
            ctx.alt_review.append(
                {
                    "source_key": ctx.source_key,
                    "reason": "unresolvable_data_uri",
                    "src": src[:80],
                    "alt": alt,
                }
            )
            continue

        absolute_url = _to_absolute_kaindl_url(src)
        if absolute_url is None:
            # Off-site or unrecognized scheme — leave as-is but surface it.
            ctx.alt_review.append(
                {
                    "source_key": ctx.source_key,
                    "reason": "non_kaindl_src_left_alone",
                    "src": src,
                    "alt": alt,
                }
            )
            continue

        manifest_row = _record_manifest(absolute_url, alt, ctx)
        img["src"] = manifest_row["public_uri"]
        # Strip the alt placeholder "[Translate to Englisch:]" (TYPO3 default).
        if alt.startswith("[Translate to Englisch:]"):
            img["alt"] = ""

    # 3. Normalize every <a href> that points at a kaindl-origin download
    #    (PDFs, DOCs, etc. under /fileadmin/). Migrated into the same
    #    public://kaindl-pages/page-bodies/<slug>/ namespace as images so the
    #    file pipeline is uniform.
    for a in list(soup.find_all("a", href=True)):
        if not isinstance(a, Tag):
            continue
        href = _attr_str(a.get("href")).strip()
        if not href or href.startswith(_PUBLIC_PREFIX):
            continue
        if href.startswith(("mailto:", "tel:", "#", "javascript:", "data:")):
            continue
        absolute_url = _to_absolute_kaindl_url(href)
        if absolute_url is None:
            continue
        # Only migrate file-like URLs (downloads). We don't rewrite in-site
        # navigation hrefs — those are canonical site paths that Drupal
        # already resolves correctly.
        if not _looks_like_download(absolute_url):
            continue
        alt = (_attr_str(a.get("title")) or a.get_text(" ", strip=True)).strip()
        manifest_row = _record_manifest(absolute_url, alt, ctx)
        a["href"] = manifest_row["public_uri"]

    # 4. Keep self-hosted animation/video/audio assets deployable with the
    #    same manifest and Drush command. Remote embeds remain iframes and are
    #    handled by harden_iframes instead of being downloaded.
    for media in list(soup.find_all(["video", "audio", "source"], src=True)):
        if not isinstance(media, Tag):
            continue
        src = _attr_str(media.get("src")).strip()
        if not src or src.startswith(_PUBLIC_PREFIX):
            continue
        absolute_url = _to_absolute_kaindl_url(src)
        if absolute_url is None or not _looks_like_download(absolute_url):
            continue
        label = _attr_str(media.get("title")).strip()
        manifest_row = _record_manifest(absolute_url, label, ctx)
        media["src"] = manifest_row["public_uri"]


def _rescue_lazy_src(img: Tag) -> None:
    src = _attr_str(img.get("src")).strip()
    if not src.startswith(_LAZY_SRC_PREFIX):
        return
    rescued = _attr_str(img.get("data-src")).strip()
    if not rescued:
        data_srcset = _attr_str(img.get("data-srcset")).strip()
        if data_srcset:
            first = data_srcset.split(",", 1)[0].strip()
            rescued = first.split(" ", 1)[0]
    if rescued:
        img["src"] = rescued


def _strip_lazy_attrs(img: Tag) -> None:
    for attr in _STRIP_ATTRS:
        if attr in img.attrs:
            del img[attr]


def _strip_lazy_classes(img: Tag) -> None:
    classes = img.get("class") or []
    kept = [c for c in classes if c not in _STRIP_CLASSES]
    if kept:
        img["class"] = kept
    elif "class" in img.attrs:
        del img["class"]


def _to_absolute_kaindl_url(src: str) -> str | None:
    """Return https://www.kaindl.com/… if src is a kaindl-origin asset, else None."""
    if src.startswith(_KAINDL_ORIGIN):
        return src
    if (
        src.startswith("http://www.kaindl.com")
        or src.startswith("https://kaindl.com")
        or src.startswith("http://kaindl.com")
    ):
        parsed = urlparse(src)
        return (
            _KAINDL_ORIGIN + parsed.path + ("?" + parsed.query if parsed.query else "")
        )
    if src.startswith("/"):
        for prefix in _MIGRATABLE_PATH_PREFIXES:
            if src.startswith(prefix):
                return _KAINDL_ORIGIN + src
    return None


_DOWNLOAD_EXTENSIONS = {
    ".pdf",
    ".doc",
    ".docx",
    ".xls",
    ".xlsx",
    ".ppt",
    ".pptx",
    ".zip",
    ".rar",
    ".7z",
    ".txt",
    ".csv",
    ".json",
    ".xml",
}

_IMAGE_EXTENSIONS = {".jpg", ".jpeg", ".png", ".gif", ".webp", ".svg", ".avif"}
_MEDIA_EXTENSIONS = {".mp4", ".webm", ".ogv", ".ogg", ".mp3", ".wav"}


def _looks_like_download(url: str) -> bool:
    parsed = urlparse(url)
    ext = os.path.splitext(unquote(parsed.path))[1].lower()
    return ext in _DOWNLOAD_EXTENSIONS or ext in _IMAGE_EXTENSIONS or ext in _MEDIA_EXTENSIONS


def _record_manifest(absolute_url: str, alt: str, ctx: TransformContext) -> dict:
    parsed = urlparse(absolute_url)
    decoded_path = unquote(parsed.path)
    ext = os.path.splitext(decoded_path)[1].lower()
    if ext not in _IMAGE_EXTENSIONS and ext not in _DOWNLOAD_EXTENSIONS and ext not in _MEDIA_EXTENSIONS:
        ext = ".jpg"
    slug_dir = ctx.slug or "root"

    for existing in ctx.manifest_rows:
        existing_path = Path(str(existing.get("local_path", "")))
        if (
            existing.get("original_url") == absolute_url
            and existing_path.parent.name == slug_dir
        ):
            return existing

    if ext in _DOWNLOAD_EXTENSIONS or ext in _MEDIA_EXTENSIONS:
        used_names: set[str] = set()
        for existing in ctx.manifest_rows:
            existing_path = Path(str(existing.get("local_path", "")))
            if existing_path.parent.name != slug_dir:
                continue
            if os.path.splitext(existing_path.name)[1].lower() in (_DOWNLOAD_EXTENSIONS | _MEDIA_EXTENSIONS):
                used_names.add(existing_path.name)
        filename = friendly_filename(absolute_url, used_names, _DOWNLOAD_EXTENSIONS | _MEDIA_EXTENSIONS)
    else:
        digest = hashlib.sha1(absolute_url.encode("utf-8")).hexdigest()[:16]
        filename = f"{digest}{ext}"

    row = {
        "source_key": ctx.source_key,
        "original_url": absolute_url,
        "local_path": f"page-bodies/{slug_dir}/{filename}",
        "public_uri": f"{_PUBLIC_PREFIX}{slug_dir}/{filename}",
        "alt": alt,
        "width": "",
        "height": "",
    }

    # Dedupe — same URL on the same page only needs one row.
    for existing in ctx.manifest_rows:
        if existing["public_uri"] == row["public_uri"]:
            return existing
    ctx.manifest_rows.append(row)
    return row
