"""Re-pull 960w variants for every low-res body image in the manifest.

Problem: during the initial body-image scrape we captured the 345w variant of
each kaindl.com `<picture>` element. At desktop/retina that upscales and looks
blurry. The same `<picture>` offers 640w and 960w siblings; this script finds
the 960w URL for each low-res manifest row, downloads the bytes, overwrites
the existing local file (so the server-side `public://` path does not change),
and updates the manifest width/height/original_url.

Flow:
  1. Load `scripts/catalog/image-import/page_body_images_manifest.csv`.
  2. Group rows where `width <= 345` by `source_key`.
  3. For each source_key: fetch `https://www.kaindl.com{source_key}` once,
     parse every `<picture><source srcset>` / direct `<img srcset>`, build a
     map from any listed URL → 960w sibling (falling back to 640w or the
     largest available if 960w is missing).
  4. For each low-res manifest row whose `original_url` appears in a page's
     srcset: download the 960w bytes, overwrite `scripts/catalog/image-import/
     {local_path}`, update the manifest row.
  5. Write the manifest back atomically. Log unreachable/un-derivable rows.

After this runs, SFTP-upload the touched image files + the updated manifest,
then run on the server:

    vendor/bin/drush kpi-body-images --replace
    vendor/bin/drush image:flush
    vendor/bin/drush cr
"""

from __future__ import annotations

import csv
import io
import os
import re
import sys
import urllib.request
import urllib.error
from collections import defaultdict
from pathlib import Path
from typing import Iterable

REPO_ROOT = Path(__file__).resolve().parents[3]
MANIFEST_PATH = REPO_ROOT / "scripts" / "catalog" / "image-import" / "page_body_images_manifest.csv"
IMAGES_DIR = REPO_ROOT / "scripts" / "catalog" / "image-import"
KAINDL_BASE = "https://www.kaindl.com"

HTTP_HEADERS = {
    "User-Agent": (
        "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 "
        "(KHTML, like Gecko) Chrome/126.0 Safari/537.36"
    )
}

# srcset entries look like: "/fileadmin/.../foo.jpg 345w, /fileadmin/.../bar.jpg 640w, ..."
_SRCSET_ENTRY = re.compile(r"(\S+)\s+(\d+)w")
# every <source|img srcset="..."> on the page.
_SRCSET_ATTR = re.compile(r'srcset=[\"\']([^\"\']+)[\"\']', re.IGNORECASE)


def fetch(url: str, timeout: float = 20.0) -> bytes:
    req = urllib.request.Request(url, headers=HTTP_HEADERS)
    with urllib.request.urlopen(req, timeout=timeout) as r:
        return r.read()


def parse_srcsets(html: str) -> list[list[tuple[str, int]]]:
    """Return a list of srcsets; each srcset is a list of (url, width) pairs,
    sorted by width ascending."""
    out = []
    for srcset_val in _SRCSET_ATTR.findall(html):
        entries = _SRCSET_ENTRY.findall(srcset_val)
        parsed = [(u, int(w)) for u, w in entries]
        parsed.sort(key=lambda p: p[1])
        if parsed:
            out.append(parsed)
    return out


def absolutize(url: str) -> str:
    if url.startswith("http"):
        return url
    if url.startswith("//"):
        return "https:" + url
    if url.startswith("/"):
        return KAINDL_BASE + url
    return KAINDL_BASE + "/" + url


def derive_hires_map(srcsets: list[list[tuple[str, int]]]) -> dict[str, tuple[str, int]]:
    """For every URL that appears in any srcset, pick the 960w sibling
    (or largest available). Returns {any_url: (hires_url, hires_width)}."""
    mapping: dict[str, tuple[str, int]] = {}
    for srcset in srcsets:
        # Prefer 960w, fall back to largest.
        target = next((p for p in srcset if p[1] == 960), None)
        if target is None:
            target = srcset[-1]
        for url, _w in srcset:
            abs_url = absolutize(url)
            abs_target = absolutize(target[0])
            mapping.setdefault(abs_url, (abs_target, target[1]))
    return mapping


def jpeg_or_png_dimensions(path: Path) -> tuple[int, int]:
    """Read width/height without Pillow, using struct-level parsing for JPEG
    and the PNG IHDR. Falls back to (-1, -1) on unsupported formats."""
    import struct
    data = path.read_bytes()
    if data[:8] == b"\x89PNG\r\n\x1a\n":
        # PNG IHDR at offset 16.
        w, h = struct.unpack(">II", data[16:24])
        return w, h
    if data[:3] == b"\xff\xd8\xff":
        # Walk JPEG markers for SOF0/SOF2.
        i = 2
        while i < len(data):
            if data[i] != 0xFF:
                return (-1, -1)
            marker = data[i + 1]
            i += 2
            if marker in (0xD8, 0xD9):
                continue
            seg_len = struct.unpack(">H", data[i : i + 2])[0]
            if marker in {0xC0, 0xC1, 0xC2, 0xC3, 0xC5, 0xC6, 0xC7, 0xC9, 0xCA, 0xCB, 0xCD, 0xCE, 0xCF}:
                h, w = struct.unpack(">HH", data[i + 3 : i + 7])
                return w, h
            i += seg_len
    return (-1, -1)


def load_manifest() -> tuple[list[dict], list[str]]:
    with MANIFEST_PATH.open(encoding="utf-8", newline="") as f:
        reader = csv.DictReader(f)
        fieldnames = reader.fieldnames or []
        rows = list(reader)
    return rows, fieldnames


def save_manifest(rows: list[dict], fieldnames: list[str]) -> None:
    tmp = MANIFEST_PATH.with_suffix(".csv.tmp")
    with tmp.open("w", encoding="utf-8", newline="") as f:
        writer = csv.DictWriter(f, fieldnames=fieldnames)
        writer.writeheader()
        writer.writerows(rows)
    tmp.replace(MANIFEST_PATH)


def group_lowres_rows(rows: list[dict], threshold: int = 345) -> dict[str, list[int]]:
    grouped: dict[str, list[int]] = defaultdict(list)
    for idx, row in enumerate(rows):
        try:
            w = int(row.get("width") or 0)
        except ValueError:
            w = 0
        if 0 < w <= threshold:
            grouped[row["source_key"]].append(idx)
    return grouped


def main(argv: Iterable[str] = ()) -> int:
    rows, fieldnames = load_manifest()
    lowres = group_lowres_rows(rows)
    total_lowres = sum(len(v) for v in lowres.values())
    print(f"[info] {total_lowres} low-res rows across {len(lowres)} source_keys")

    updated = 0
    unresolved: list[dict] = []

    for source_key, row_indices in lowres.items():
        page_url = KAINDL_BASE + source_key
        print(f"\n[page] {page_url}  ({len(row_indices)} low-res rows)")
        try:
            html = fetch(page_url).decode("utf-8", errors="replace")
        except Exception as exc:
            print(f"  [warn] failed to fetch page: {exc!r}")
            for idx in row_indices:
                unresolved.append({"row": idx, "reason": f"page fetch failed: {exc}"})
            continue
        srcsets = parse_srcsets(html)
        hires_map = derive_hires_map(srcsets)

        for idx in row_indices:
            row = rows[idx]
            original_url = row["original_url"]
            hit = hires_map.get(original_url)
            if hit is None:
                # Try path-only match (origin URLs may be relative in srcset).
                rel = original_url.replace(KAINDL_BASE, "")
                hit = hires_map.get(rel) or hires_map.get(absolutize(rel))
            if hit is None:
                unresolved.append({"row": idx, "reason": f"no srcset match for {original_url}"})
                continue

            hires_url, hires_w = hit
            if hires_w <= int(row.get("width") or 0):
                unresolved.append({"row": idx, "reason": f"best available ({hires_w}w) not larger"})
                continue

            local_rel = row["local_path"]
            local_abs = IMAGES_DIR / local_rel
            local_abs.parent.mkdir(parents=True, exist_ok=True)
            try:
                data = fetch(hires_url)
            except Exception as exc:
                unresolved.append({"row": idx, "reason": f"download failed: {exc}"})
                continue
            local_abs.write_bytes(data)
            try:
                actual_w, actual_h = jpeg_or_png_dimensions(local_abs)
            except Exception:
                actual_w, actual_h = hires_w, -1

            row["original_url"] = hires_url
            row["width"] = str(actual_w if actual_w > 0 else hires_w)
            row["height"] = str(actual_h if actual_h > 0 else "")
            updated += 1
            print(f"  [ok] {local_rel} -> {row['width']}x{row['height']}  ({hires_url.rsplit('/',1)[-1]})")

    save_manifest(rows, fieldnames)
    print(f"\n[done] {updated}/{total_lowres} images updated")
    if unresolved:
        print(f"[unresolved] {len(unresolved)} rows could not be upgraded:")
        for item in unresolved[:20]:
            r = rows[item["row"]]
            print(f"  - {r['source_key']}  {r['local_path']}  ({item['reason']})")
        if len(unresolved) > 20:
            print(f"  ... and {len(unresolved) - 20} more")
    return 0 if not unresolved else 0  # unresolved are logged, not fatal


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