"""PDF -> PNG/JPG via pypdfium2 + Pillow (TZ 2.6.8). PDFium is not thread-safe: calls are serialised."""

from __future__ import annotations

import io
import threading
from dataclasses import dataclass

from .errors import RenderError

_PDFIUM_LOCK = threading.Lock()
MAX_PIXELS = 40_000_000


@dataclass
class RasterPage:
    index: int
    data: bytes
    width: int
    height: int


def raster_available() -> bool:
    try:
        import pypdfium2  # noqa: F401
    except Exception:
        return False
    return True


def parse_page_ranges(spec: str | list[int] | None, total: int) -> list[int]:
    """``"1-3,5"`` -> [0, 1, 2, 4] (0-based, clipped to the document)."""
    if spec is None or spec == "" or spec == "all":
        return list(range(total))
    if isinstance(spec, list):
        return [p - 1 for p in spec if 1 <= int(p) <= total]
    out: list[int] = []
    for part in str(spec).split(","):
        part = part.strip()
        if not part:
            continue
        if "-" in part:
            a, b = part.split("-", 1)
            lo, hi = int(a or 1), int(b or total)
            out.extend(i - 1 for i in range(lo, hi + 1) if 1 <= i <= total)
        elif part.isdigit() and 1 <= int(part) <= total:
            out.append(int(part) - 1)
    seen: set[int] = set()
    return [p for p in out if not (p in seen or seen.add(p))]


def rasterize(
    pdf: bytes,
    *,
    fmt: str = "png",
    dpi: int = 150,
    quality: int = 85,
    pages: list[int] | None = None,
    background: str = "#FFFFFF",
    max_pixels: int = MAX_PIXELS,
) -> list[RasterPage]:
    try:
        import pypdfium2 as pdfium
    except Exception as exc:  # pragma: no cover - platform without wheel
        raise RenderError("RASTER_UNAVAILABLE", "pypdfium2 is not available on this platform") from exc
    dpi = max(36, min(600, int(dpi)))
    scale = dpi / 72.0
    out: list[RasterPage] = []
    bg = background.lstrip("#")
    fill = (int(bg[0:2], 16), int(bg[2:4], 16), int(bg[4:6], 16), 255)
    with _PDFIUM_LOCK:
        doc = pdfium.PdfDocument(pdf)
        try:
            indices = pages if pages is not None else list(range(len(doc)))
            for i in indices:
                page = doc[i]
                try:
                    w_pt, h_pt = page.get_size()
                    if (w_pt * scale) * (h_pt * scale) > max_pixels:
                        raise RenderError("RASTER_TOO_LARGE", f"Page {i + 1} exceeds {max_pixels} pixels at {dpi} DPI")
                    bitmap = page.render(scale=scale, fill_color=fill if fmt == "jpg" else (255, 255, 255, 255))
                    try:
                        img = bitmap.to_pil()
                        buf = io.BytesIO()
                        if fmt == "jpg":
                            img.convert("RGB").save(buf, "JPEG", quality=int(quality), optimize=True)
                        else:
                            img.save(buf, "PNG", compress_level=6)
                        out.append(RasterPage(i, buf.getvalue(), img.width, img.height))
                        img.close()
                    finally:
                        bitmap.close()
                finally:
                    page.close()
        finally:
            doc.close()
    return out
