"""SVG images: sanitising on upload and vector drawing into the PDF (svglib: pure Python, no cairo on shared hosting)."""

from __future__ import annotations

import io
import logging
import re
import threading
import xml.etree.ElementTree as StdTree
from pathlib import Path
from typing import Any

from defusedxml import ElementTree
from defusedxml.common import DefusedXmlException

SVG_NS = "http://www.w3.org/2000/svg"
XLINK_NS = "http://www.w3.org/1999/xlink"
MAX_ELEMENTS = 50_000
DEFAULT_SIZE = (300, 150)
_FORBIDDEN = {"script", "foreignobject", "iframe", "object", "embed", "audio", "video", "animate", "animatemotion", "animatetransform", "set", "handler", "listener"}
_UNSAFE_CSS = re.compile(r"@import|expression\s*\(|url\(\s*['\"]?(?!#|data:image/)", re.I)
_UNITS = {"": 1.0, "px": 1.0, "pt": 4 / 3, "pc": 16.0, "mm": 96 / 25.4, "cm": 96 / 2.54, "in": 96.0}
_LENGTH = re.compile(r"^\s*([0-9.]+)\s*([a-z]*)\s*$", re.I)
_DRAWINGS: dict[str, Any] = {}
_LOCK = threading.Lock()
# svglib logs every unsupported construct; the render log is not the place for it
logging.getLogger("svglib.svglib").setLevel(logging.ERROR)


class SvgError(ValueError):
    pass


def looks_like_svg(path: str | None = None, data: bytes | None = None) -> bool:
    if path and not data:
        if Path(path).suffix.lower() == ".svg":
            return True
        with open(path, "rb") as fh:
            data = fh.read(2048)
    head = (data or b"")[:2048].lstrip(b"\xef\xbb\xbf \t\r\n").lower()
    return head.startswith(b"<") and b"<svg" in head


def _local(tag: Any) -> str:
    return tag.rsplit("}", 1)[-1].lower() if isinstance(tag, str) else ""


def _parse(data: bytes) -> Any:
    try:
        root = ElementTree.fromstring(data)
    except (ElementTree.ParseError, DefusedXmlException, ValueError) as exc:
        raise SvgError("not a well-formed SVG") from exc
    if _local(root.tag) != "svg":
        raise SvgError("root element is not <svg>")
    return root


def _length(raw: str | None) -> float | None:
    m = _LENGTH.match(raw or "")
    if not m or m.group(2).lower() not in _UNITS:
        return None
    value = float(m.group(1)) * _UNITS[m.group(2).lower()]
    return value if value > 0 else None


def _viewbox(root: Any) -> tuple[float, float] | None:
    parts = re.split(r"[\s,]+", (root.get("viewBox") or "").strip())
    try:
        w, h = float(parts[2]), float(parts[3])
    except (IndexError, ValueError):
        return None
    return (w, h) if w > 0 and h > 0 else None


def _root_size(root: Any) -> tuple[float, float]:
    w, h = _length(root.get("width")), _length(root.get("height"))
    box = _viewbox(root)
    if w and h:
        return w, h
    if box:
        if w:
            return w, w * box[1] / box[0]
        if h:
            return h * box[0] / box[1], h
        return box
    return float(DEFAULT_SIZE[0]), float(DEFAULT_SIZE[1])


def svg_size(data: bytes) -> tuple[int, int]:
    w, h = _root_size(_parse(data))
    return max(1, round(w)), max(1, round(h))


def _clean(el: Any, counter: list[int]) -> None:
    counter[0] += 1
    if counter[0] > MAX_ELEMENTS:
        raise SvgError("too many elements")
    for attr, value in list(el.attrib.items()):
        name = _local(attr)
        if name.startswith("on"):
            del el.attrib[attr]
        elif name == "href" and not value.startswith(("#", "data:image/")):
            del el.attrib[attr]
        elif _UNSAFE_CSS.search(value) and name in ("style", "fill", "stroke", "filter", "mask", "clip-path"):
            del el.attrib[attr]
    if _local(el.tag) == "style" and _UNSAFE_CSS.search(el.text or ""):
        el.text = ""
    for child in list(el):
        if _local(child.tag) in _FORBIDDEN:
            el.remove(child)
        else:
            _clean(child, counter)


def sanitize_svg(data: bytes) -> tuple[bytes, tuple[int, int]]:
    """Strip anything active or external; the root always gets width, height and viewBox (browsers need them)."""
    root = _parse(data)
    w, h = _root_size(root)
    _clean(root, [0])
    if not _viewbox(root):
        root.set("viewBox", f"0 0 {w:g} {h:g}")
    root.set("width", f"{w:g}")
    root.set("height", f"{h:g}")
    # the default namespace stays unprefixed in the output
    StdTree.register_namespace("", SVG_NS)
    StdTree.register_namespace("xlink", XLINK_NS)
    out = StdTree.tostring(root, encoding="utf-8", xml_declaration=True)
    return out, (max(1, round(w)), max(1, round(h)))


def _load(path: str | None, data: bytes | None) -> Any:
    from svglib.svglib import svg2rlg

    try:
        drawing = svg2rlg(path) if path else svg2rlg(io.BytesIO(data or b""))
    except Exception as exc:  # svglib raises many things on bad input
        raise SvgError(f"cannot read SVG: {exc}") from exc
    if drawing is None:
        raise SvgError("cannot read SVG")
    return drawing


def _drawing(ref: Any) -> Any:
    with _LOCK:
        hit = _DRAWINGS.get(ref.key)
    if hit is not None:
        return hit
    drawing = _load(ref.path, ref.data)
    with _LOCK:
        if len(_DRAWINGS) > 64:
            _DRAWINGS.clear()
        _DRAWINGS[ref.key] = drawing
    return drawing


def draw_svg(c: Any, ref: Any, w: float, h: float) -> None:
    """Draw into the box (0, 0, w, h) of the current y-up transform. A broken file leaves the box empty."""
    from reportlab.graphics import renderPDF

    try:
        drawing = _drawing(ref)
    except SvgError:
        return
    c.saveState()
    c.scale(w / max(float(drawing.width), 1e-6), h / max(float(drawing.height), 1e-6))
    renderPDF.draw(drawing, c, 0, 0)
    c.restoreState()


def svg_thumbnail(data: bytes, side: int) -> bytes:
    """PNG preview: through a one-page PDF and pdfium, the same path as the rendered documents."""
    import pypdfium2
    from reportlab.graphics import renderPDF
    from reportlab.pdfgen.canvas import Canvas

    drawing = _load(None, data)
    w, h = max(float(drawing.width), 1.0), max(float(drawing.height), 1.0)
    pdf = io.BytesIO()
    canvas = Canvas(pdf, pagesize=(w, h))
    renderPDF.draw(drawing, canvas, 0, 0)
    canvas.showPage()
    canvas.save()
    doc = pypdfium2.PdfDocument(pdf.getvalue())
    try:
        image = doc[0].render(scale=side / max(w, h), fill_color=(0, 0, 0, 0)).to_pil()
    finally:
        doc.close()
    buf = io.BytesIO()
    image.convert("RGBA").save(buf, "PNG", optimize=True)
    return buf.getvalue()
