"""ReportLab drawing backend (TZ 2.6.6-2.6.9): pages of draw nodes -> PDF bytes.

Only the low-level ``pdfgen.canvas`` API is used (no Platypus, no ``simpleSplit``): every glyph run is
placed at coordinates computed by the shared text layout.

Coordinates: each page starts with the matrix ``[1 0 0 -1 0 H]`` so that drawing happens in the scene's
y-down space (origin = top-left of the trim box). Glyphs and images are re-flipped locally (text matrix
``[1 0 0 -1 x y]``, image ``cm``), so nothing is mirrored. Rotation is clockwise in degrees, around
``origin`` (fractions of the node box).
"""

from __future__ import annotations

import io
import math
import threading
from typing import Any

from reportlab.lib.utils import ImageReader
from reportlab.pdfbase import pdfmetrics
from reportlab.pdfbase.ttfonts import TTFont
from reportlab.pdfgen.canvas import Canvas

from .. import ENGINE_VERSION
from ..errors import RenderError, Warnings
from ..model import DrawNode, Page
from ..providers import FontProvider, ImageRef
from ..svg import draw_svg
from .colors import parse_color

KAPPA = 0.5523  # bezier circle approximation shared with the editor (TZ 2.6.6 p.1)
_CAPS = {"butt": 0, "round": 1, "square": 2}
_JOINS = {"miter": 0, "round": 1, "bevel": 2}
_BLEND = {
    "multiply": "Multiply",
    "screen": "Screen",
    "overlay": "Overlay",
    "darken": "Darken",
    "lighten": "Lighten",
}

_FONT_LOCK = threading.Lock()
_REGISTERED: dict[str, str] = {}
_IMAGE_READERS: dict[str, ImageReader] = {}
_IMAGE_LOCK = threading.Lock()


def register_font(fonts: FontProvider, key: str) -> str:
    """Register the font's ``pdf.ttf`` once per process (TZ 2.6.4 p.4); returns ReportLab font name."""
    name = _REGISTERED.get(key)
    if name is not None:
        return name
    with _FONT_LOCK:
        name = _REGISTERED.get(key)
        if name is None:
            face = fonts.face(key)
            import hashlib

            name = "F" + hashlib.sha1(f"{face.key}:{face.pdf_path}".encode()).hexdigest()[:12]
            try:
                pdfmetrics.getFont(name)
            except KeyError:
                try:
                    pdfmetrics.registerFont(TTFont(name, face.pdf_path))
                except Exception as exc:
                    raise RenderError("FONT_LOAD_FAILED", f"Cannot load font {face.family}: {exc}") from exc
            _REGISTERED[key] = name
    return name


def _image_reader(ref: ImageRef) -> ImageReader | str:
    if ref.path:
        return ref.path
    with _IMAGE_LOCK:
        reader = _IMAGE_READERS.get(ref.key)
        if reader is None:
            reader = ImageReader(io.BytesIO(ref.data or b""))
            if len(_IMAGE_READERS) > 64:
                _IMAGE_READERS.clear()
            _IMAGE_READERS[ref.key] = reader
    return reader


def rounded_rect_path(c: Canvas, w: float, h: float, radius: Any) -> Any:
    p = c.beginPath()
    if isinstance(radius, (list, tuple)) and len(radius) == 4:
        tl, tr, br, bl = (float(r or 0) for r in radius)
    else:
        tl = tr = br = bl = float(radius or 0)
    lim = min(w, h) / 2
    tl, tr, br, bl = (max(0.0, min(r, lim)) for r in (tl, tr, br, bl))
    if not (tl or tr or br or bl):
        p.rect(0, 0, w, h)
        return p
    k = KAPPA
    p.moveTo(tl, 0)
    p.lineTo(w - tr, 0)
    if tr:
        p.curveTo(w - tr + tr * k, 0, w, tr - tr * k, w, tr)
    p.lineTo(w, h - br)
    if br:
        p.curveTo(w, h - br + br * k, w - br + br * k, h, w - br, h)
    p.lineTo(bl, h)
    if bl:
        p.curveTo(bl - bl * k, h, 0, h - bl + bl * k, 0, h - bl)
    p.lineTo(0, tl)
    if tl:
        p.curveTo(0, tl - tl * k, tl - tl * k, 0, tl, 0)
    p.close()
    return p


def _arc_segments(cx: float, cy: float, rx: float, ry: float, a0: float, a1: float) -> list[tuple[float, ...]]:
    """Cubic bezier segments for an elliptical arc, angles in degrees clockwise (y-down)."""
    segs: list[tuple[float, ...]] = []
    total = a1 - a0
    n = max(1, math.ceil(abs(total) / 90.0))
    step = math.radians(total / n)
    t = math.radians(a0)
    for _ in range(n):
        k = 4.0 / 3.0 * math.tan(step / 4)
        c0, s0 = math.cos(t), math.sin(t)
        c1, s1 = math.cos(t + step), math.sin(t + step)
        segs.append(
            (
                cx + rx * (c0 - k * s0),
                cy + ry * (s0 + k * c0),
                cx + rx * (c1 + k * s1),
                cy + ry * (s1 - k * c1),
                cx + rx * c1,
                cy + ry * s1,
            )
        )
        t += step
    return segs


def ellipse_path(c: Canvas, w: float, h: float, arc: tuple[float, float, float] | None) -> Any:
    p = c.beginPath()
    cx, cy, rx, ry = w / 2, h / 2, w / 2, h / 2
    start, end, inner = arc if arc else (0.0, 360.0, 0.0)
    full = abs(end - start) >= 360 - 1e-6
    if full and inner <= 0:
        p.ellipse(0, 0, w, h)
        return p
    p.moveTo(cx + rx * math.cos(math.radians(start)), cy + ry * math.sin(math.radians(start)))
    for seg in _arc_segments(cx, cy, rx, ry, start, end):
        p.curveTo(*seg)
    if inner > 0:
        irx, iry = rx * inner, ry * inner
        if full:
            p.close()
            p.moveTo(cx + irx * math.cos(math.radians(end)), cy + iry * math.sin(math.radians(end)))
        else:
            p.lineTo(cx + irx * math.cos(math.radians(end)), cy + iry * math.sin(math.radians(end)))
        for seg in _arc_segments(cx, cy, irx, iry, end, start):
            p.curveTo(*seg)
    else:
        p.lineTo(cx, cy)
    p.close()
    return p


class PdfWriter:
    def __init__(
        self,
        fonts: FontProvider,
        warnings: Warnings,
        *,
        deterministic: bool = False,
        kerning: bool = True,
        meta: dict[str, str] | None = None,
        watermark: str | None = None,
    ) -> None:
        self.fonts = fonts
        self.warnings = warnings
        self.deterministic = deterministic
        self.kerning = kerning
        self.meta = meta or {}
        self.watermark = watermark
        self.c: Canvas | None = None

    # ------------------------------------------------------------------ document
    def write(self, pages: list[Page]) -> bytes:
        buf = io.BytesIO()
        first = pages[0] if pages else None
        size = (first.w + 2 * first.bleed, first.h + 2 * first.bleed) if first else (595.28, 841.89)
        c = Canvas(buf, pagesize=size, pageCompression=1, invariant=1 if self.deterministic else 0)
        self.c = c
        c.setCreator(f"Snapfile {ENGINE_VERSION}")
        c.setProducer("ReportLab")
        if self.meta.get("title"):
            c.setTitle(self.meta["title"])
        if self.meta.get("author"):
            c.setAuthor(self.meta["author"])
        if self.meta.get("subject"):
            c.setSubject(self.meta["subject"])
        if self.meta.get("keywords"):
            c.setKeywords(self.meta["keywords"])
        for page in pages:
            self._page(page)
        c.save()
        return buf.getvalue()

    def _page(self, page: Page) -> None:
        c = self.c
        assert c is not None
        b = page.bleed
        c.setPageSize((page.w + 2 * b, page.h + 2 * b))
        if b > 0:
            c.setTrimBox((b, b, b + page.w, b + page.h))
            c.setBleedBox((0, 0, page.w + 2 * b, page.h + 2 * b))
        c.saveState()
        c.transform(1, 0, 0, -1, b, page.h + b)
        if page.background:
            c.saveState()
            c.translate(-b, -b)
            p = c.beginPath()
            p.rect(0, 0, page.w + 2 * b, page.h + 2 * b)
            self._fill_paint(page.background, p, page.w + 2 * b, page.h + 2 * b, 1.0, 0)
            c.restoreState()
        for item in page.items:
            self._node(item, 1.0)
        if self.watermark:
            self._watermark(page)
        c.restoreState()
        c.showPage()

    def _watermark(self, page: Page) -> None:
        c = self.c
        assert c is not None
        key = self.fonts.resolve(None, None, 700, "normal")
        name = register_font(self.fonts, key)
        c.saveState()
        c.setFillColorRGB(0.85, 0.1, 0.1)
        c.setFillAlpha(0.18)
        c.translate(page.w / 2, page.h / 2)
        c.rotate(-30)
        c.transform(1, 0, 0, -1, 0, 0)
        c.setFont(name, 96)
        c.drawCentredString(0, -30, self.watermark or "")
        c.restoreState()

    # ------------------------------------------------------------------ nodes
    def _node(self, n: DrawNode, alpha: float) -> None:
        c = self.c
        assert c is not None
        c.saveState()
        c.translate(n.x, n.y)
        if n.rotation:
            ox, oy = n.w * n.origin[0], n.h * n.origin[1]
            c.translate(ox, oy)
            c.rotate(n.rotation)
            c.translate(-ox, -oy)
        a = alpha * n.opacity
        if n.blend != "normal" and n.blend in _BLEND and hasattr(c, "setBlendMode"):
            c.setBlendMode(_BLEND[n.blend])
        kind = n.kind
        if kind in ("rect", "frame"):
            path = rounded_rect_path(c, n.w, n.h, n.radius)
            self._fills(n, path, a)
            if n.children:
                if n.clip:
                    c.saveState()
                    c.clipPath(rounded_rect_path(c, n.w, n.h, n.radius), stroke=0, fill=0)
                for child in n.children:
                    self._node(child, a)
                if n.clip:
                    c.restoreState()
            self._outline(n, path, a)
        elif kind == "group":
            if n.clip and n.children:
                c.saveState()
                p = c.beginPath()
                p.rect(0, 0, n.w, n.h)
                c.clipPath(p, stroke=0, fill=0)
            for child in n.children:
                self._node(child, a)
            if n.clip and n.children:
                c.restoreState()
        elif kind == "ellipse":
            path = ellipse_path(c, n.w, n.h, n.arc)
            self._fills(n, path, a, even_odd=bool(n.arc and n.arc[2] > 0))
            self._strokes(n, path, a)
        elif kind == "line":
            p = c.beginPath()
            (x0, y0), (x1, y1) = n.points[0], n.points[-1]
            p.moveTo(x0, y0)
            p.lineTo(x1, y1)
            self._strokes(n, p, a)
        elif kind == "path":
            p = c.beginPath()
            for seg in n.path:
                if seg[0] == "M":
                    p.moveTo(seg[1], seg[2])
                elif seg[0] == "L":
                    p.lineTo(seg[1], seg[2])
                elif seg[0] == "C":
                    p.curveTo(*seg[1:])
                else:
                    p.close()
            self._fills(n, p, a)
            self._strokes(n, p, a)
        elif kind == "text":
            if n.fills:
                self._fills(n, rounded_rect_path(c, n.w, n.h, n.radius), a)
            self._text(n, a)
        elif kind == "image":
            self._image(n, a)
        c.restoreState()

    def _fills(self, n: DrawNode, path: Any, alpha: float, even_odd: bool = False) -> None:
        for paint in n.fills:
            self._fill_paint(paint, path, n.w, n.h, alpha, 1 if even_odd else 0, radius=n.radius)

    def _fill_paint(
        self, paint: dict[str, Any], path: Any, w: float, h: float, alpha: float, fill_mode: int, radius: Any = 0
    ) -> None:
        c = self.c
        assert c is not None
        ptype = paint.get("type", "solid")
        pa = alpha * float(paint.get("opacity", 1.0))
        if pa <= 0:
            return
        if ptype == "solid":
            rgb, ca, cmyk = parse_color(paint.get("color"))
            if cmyk:
                c.setFillColorCMYK(*cmyk)
            else:
                c.setFillColorRGB(*rgb)
            c.setFillAlpha(pa * ca)
            c.drawPath(path, stroke=0, fill=1, fillMode=fill_mode)
        elif ptype in ("linear", "radial"):
            stops = paint.get("stops") or []
            if len(stops) < 2:
                return
            colors = []
            positions = []
            for s in stops:
                rgb, _, _ = parse_color(s.get("color"))
                from reportlab.lib.colors import Color

                colors.append(Color(*rgb))
                positions.append(max(0.0, min(1.0, float(s.get("offset", 0)))))
            c.saveState()
            c.setFillAlpha(pa)
            c.clipPath(path, stroke=0, fill=0, fillMode=fill_mode)
            if ptype == "linear":
                ang = math.radians(float(paint.get("angle", 90)))
                dx, dy = math.sin(ang), -math.cos(ang)
                half = (abs(w * dx) + abs(h * dy)) / 2
                cx, cy = w / 2, h / 2
                c.linearGradient(
                    cx - dx * half, cy - dy * half, cx + dx * half, cy + dy * half, colors, positions, extend=True
                )
            else:
                center = paint.get("center") or {}
                rx = float(center.get("x", 0.5)) * w
                ry = float(center.get("y", 0.5)) * h
                radius_v = float(paint.get("radius", 0.5)) * max(w, h)
                c.radialGradient(rx, ry, radius_v, colors, positions, extend=True)
            c.restoreState()
        elif ptype == "image":
            ref = paint.get("_ref")
            if ref is None:
                return
            c.saveState()
            c.clipPath(path, stroke=0, fill=0, fillMode=fill_mode)
            self._draw_image(ref, w, h, paint.get("fit", "cover"), paint.get("focal", (0.5, 0.5)), pa)
            c.restoreState()

    def _outline(self, n: DrawNode, path: Any, alpha: float) -> None:
        """Whole outline, or only ``strokeSides`` (corner radius does not apply to a partial outline)."""
        sides = n.stroke_sides
        if sides is None:
            self._strokes(n, path, alpha)
            return
        if not sides or not n.strokes:
            return
        c = self.c
        assert c is not None
        segments = {
            "top": (0.0, 0.0, n.w, 0.0),
            "right": (n.w, 0.0, n.w, n.h),
            "bottom": (0.0, n.h, n.w, n.h),
            "left": (0.0, 0.0, 0.0, n.h),
        }
        p = c.beginPath()
        for side in sides:
            x0, y0, x1, y1 = segments[side]
            p.moveTo(x0, y0)
            p.lineTo(x1, y1)
        self._strokes(n, p, alpha)

    def _strokes(self, n: DrawNode, path: Any, alpha: float) -> None:
        c = self.c
        assert c is not None
        for s in n.strokes:
            if s["width"] <= 0:
                continue
            rgb, ca, cmyk = parse_color(s["color"])
            if cmyk:
                c.setStrokeColorCMYK(*cmyk)
            else:
                c.setStrokeColorRGB(*rgb)
            c.setStrokeAlpha(alpha * ca * s.get("opacity", 1.0))
            c.setLineWidth(s["width"])
            c.setLineCap(_CAPS.get(s["cap"], 0))
            c.setLineJoin(_JOINS.get(s["join"], 0))
            c.setMiterLimit(s["miterLimit"])
            c.setDash(s["dash"] or [], 0)
            c.drawPath(path, stroke=1, fill=0)

    # ------------------------------------------------------------------ images
    def _image(self, n: DrawNode, alpha: float) -> None:
        c = self.c
        assert c is not None
        c.saveState()
        clip = n.fit in ("cover", "none") or bool(n.radius)
        if clip:
            c.clipPath(rounded_rect_path(c, n.w, n.h, n.radius), stroke=0, fill=0)
        self._draw_image(n.image, n.w, n.h, n.fit, n.focal, alpha)
        c.restoreState()
        if n.strokes:
            self._outline(n, rounded_rect_path(c, n.w, n.h, n.radius), alpha)

    def _draw_image(
        self, ref: ImageRef, w: float, h: float, fit: str, focal: tuple[float, float], alpha: float
    ) -> None:
        c = self.c
        assert c is not None
        iw, ih = max(1, ref.width), max(1, ref.height)
        if fit == "fill":
            dx, dy, dw, dh = 0.0, 0.0, w, h
        elif fit == "contain":
            s = min(w / iw, h / ih)
            dw, dh = iw * s, ih * s
            dx, dy = (w - dw) / 2, (h - dh) / 2
        elif fit == "none":
            dw, dh = iw * 0.75, ih * 0.75
            dx, dy = (w - dw) / 2, (h - dh) / 2
        else:
            s = max(w / iw, h / ih)
            dw, dh = iw * s, ih * s
            dx, dy = (w - dw) * focal[0], (h - dh) * focal[1]
        c.saveState()
        if alpha < 1:
            c.setFillAlpha(alpha)
        c.transform(1, 0, 0, -1, dx, dy + dh)
        if ref.vector:
            draw_svg(c, ref, dw, dh)
        else:
            c.drawImage(_image_reader(ref), 0, 0, dw, dh, mask="auto")
        c.restoreState()

    # ------------------------------------------------------------------ text
    def _text(self, n: DrawNode, alpha: float) -> None:
        c = self.c
        assert c is not None
        layout = n.text
        if not layout or not layout["lines"]:
            return
        scale = float(layout.get("scale", 1.0))
        styles = n.text_runs
        decorations: list[tuple[float, float, float, float, tuple[float, float, float], float, Any]] = []
        t = c.beginText()
        current_font: tuple[str, float] | None = None
        current_color: tuple[Any, ...] | None = None
        current_ls: float | None = None
        for line in layout["lines"]:
            baseline = float(line["baseline"])
            word_extra = float(line.get("wordSpacing", 0) or 0)
            for gr in line["runs"]:
                st = styles[gr["run"]] if 0 <= gr["run"] < len(styles) else styles[-1]
                key = st["fontKey"]
                name = register_font(self.fonts, key)
                metrics = self.fonts.metrics(key)
                size = float(st["fontSize"]) * scale
                ls = float(st.get("letterSpacing") or 0)
                rgb, ca, cmyk = parse_color(st.get("color"))
                color_key = (rgb, ca, cmyk)
                if current_font != (name, size):
                    t.setFont(name, size)
                    current_font = (name, size)
                if current_ls != ls:
                    t.setCharSpace(ls)
                    current_ls = ls
                if current_color != color_key:
                    if cmyk:
                        t.setFillColorCMYK(*cmyk)
                    else:
                        t.setFillColorRGB(*rgb)
                    c.setFillAlpha(alpha * ca)
                    current_color = color_key
                end_x = self._glyph_run(t, gr["text"], float(gr["x"]), baseline, metrics, size, ls, word_extra)
                if st.get("underline") or st.get("strike"):
                    upm = metrics.upm
                    thick = max(0.5, metrics.underline_thickness * size / upm)
                    if st.get("underline"):
                        y = baseline - metrics.underline_position * size / upm
                        decorations.append((float(gr["x"]), end_x, y, thick, rgb, alpha * ca, cmyk))
                    if st.get("strike"):
                        y = baseline - (metrics.x_height or upm * 0.5) * 0.5 * size / upm
                        decorations.append((float(gr["x"]), end_x, y, thick, rgb, alpha * ca, cmyk))
        c.drawText(t)
        for x0, x1, y, thick, rgb, a, cmyk in decorations:
            if cmyk:
                c.setStrokeColorCMYK(*cmyk)
            else:
                c.setStrokeColorRGB(*rgb)
            c.setStrokeAlpha(a)
            c.setLineWidth(thick)
            c.setDash([], 0)
            c.line(x0, y, x1, y)

    def _glyph_run(
        self, t: Any, text: str, x: float, baseline: float, metrics: Any, size: float, ls: float, word_extra: float
    ) -> float:
        """Emit a glyph run split at spaces and kerning points; each segment gets an explicit Tm.

        Segmenting at word boundaries also bounds the drift between our float advances and the
        integer /W widths ReportLab writes into the font dictionary.
        """
        upm = metrics.upm
        cursor = x
        seg: list[str] = []
        seg_x = x
        prev = -1
        for ch in text:
            cp = ord(ch)
            if ch == " ":
                if seg:
                    t.setTextTransform(1, 0, 0, -1, seg_x, baseline)
                    t.textOut("".join(seg))
                    seg = []
                cursor += (metrics.advance(cp) * size) / upm + ls + word_extra
                prev = -1
                continue
            k = metrics.kern(prev, cp) if (self.kerning and prev >= 0) else 0
            if k:
                if seg:
                    t.setTextTransform(1, 0, 0, -1, seg_x, baseline)
                    t.textOut("".join(seg))
                    seg = []
                cursor += (k * size) / upm
            if not seg:
                seg_x = cursor
            seg.append(ch)
            cursor += (metrics.advance(cp) * size) / upm + ls
            prev = cp
        if seg:
            t.setTextTransform(1, 0, 0, -1, seg_x, baseline)
            t.textOut("".join(seg))
        return cursor
