"""Resource providers used by the engine (TZ 2.6.1): fonts and images.

The engine never touches the database or Django storage; the application passes adapters implementing
these protocols. ``FontLibrary`` and ``MappingAssetResolver`` are ready-made implementations over local
files, used by the Django adapter, tests and benchmarks.
"""

from __future__ import annotations

import base64
import binascii
import io
import threading
from collections.abc import Iterable
from dataclasses import dataclass, field
from pathlib import Path
from typing import Any, Protocol

from .fontmetrics import FontMetrics
from .svg import looks_like_svg, svg_size

BUNDLED_FONTS_DIR = Path(__file__).parent / "fonts"


@dataclass(frozen=True)
class FontFace:
    key: str
    family: str
    weight: int
    style: str
    metrics_path: str
    pdf_path: str
    ids: tuple[str, ...] = ()


class FontProvider(Protocol):
    def resolve(self, font_id: str | None, family: str | None, weight: int, style: str) -> str: ...

    def metrics(self, key: str) -> FontMetrics: ...

    def face(self, key: str) -> FontFace: ...


_METRICS_CACHE: dict[str, FontMetrics] = {}
_METRICS_LOCK = threading.Lock()


def load_metrics(key: str, path: str) -> FontMetrics:
    """Process-wide metrics cache (TZ 2.6.4 p.6)."""
    cache_key = f"{key}:{path}"
    m = _METRICS_CACHE.get(cache_key)
    if m is None:
        with _METRICS_LOCK:
            m = _METRICS_CACHE.get(cache_key)
            if m is None:
                m = FontMetrics.from_file(key, path)
                _METRICS_CACHE[cache_key] = m
    return m


@dataclass
class FontLibrary:
    """Set of prepared font faces with deterministic face matching.

    Matching (shared with the editor): exact ``fontId`` -> that face's family; within the family pick the
    same style if available, then the weight with minimal ``|w - wanted|`` (ties -> the heavier one).
    Unknown family -> ``default_family``.
    """

    faces: list[FontFace] = field(default_factory=list)
    default_family: str = "Inter"

    def __post_init__(self) -> None:
        self._by_key = {f.key: f for f in self.faces}
        self._by_id: dict[str, FontFace] = {}
        for f in self.faces:
            for i in f.ids:
                self._by_id[i] = f
        self._families: dict[str, list[FontFace]] = {}
        for f in self.faces:
            self._families.setdefault(f.family.lower(), []).append(f)
        self._resolve_cache: dict[tuple[Any, ...], str] = {}

    def add(self, face: FontFace) -> None:
        self.faces.append(face)
        self.__post_init__()

    def face(self, key: str) -> FontFace:
        return self._by_key[key]

    def metrics(self, key: str) -> FontMetrics:
        f = self._by_key[key]
        return load_metrics(f.key, f.metrics_path)

    def has_family(self, family: str) -> bool:
        return family.lower() in self._families

    def resolve(self, font_id: str | None, family: str | None, weight: int, style: str) -> str:
        ck = (font_id, family, weight, style)
        hit = self._resolve_cache.get(ck)
        if hit is not None:
            return hit
        candidates: list[FontFace] | None = None
        if font_id and font_id in self._by_id:
            base = self._by_id[font_id]
            candidates = self._families.get(base.family.lower())
        if not candidates and family:
            candidates = self._families.get(family.lower())
        if not candidates:
            candidates = self._families.get(self.default_family.lower()) or self.faces
        if not candidates:
            raise LookupError("No fonts available")
        same_style = [f for f in candidates if f.style == style] or candidates
        best = min(same_style, key=lambda f: (abs(f.weight - weight), -f.weight))
        self._resolve_cache[ck] = best.key
        return best.key


@dataclass(frozen=True)
class ImageRef:
    """A local image usable by ReportLab: a file path or raw bytes, with pixel size."""

    key: str
    path: str | None = None
    data: bytes | None = None
    width: int = 0
    height: int = 0
    vector: bool = False

    def open(self) -> Any:
        return self.path if self.path else io.BytesIO(self.data or b"")


class AssetResolver(Protocol):
    def image(self, asset_id: str) -> ImageRef | None: ...

    def fetch(self, src: str) -> ImageRef | None: ...


def image_size(path: str | None = None, data: bytes | None = None) -> tuple[int, int]:
    from PIL import Image

    if looks_like_svg(path=path, data=data):
        return svg_size(Path(path).read_bytes() if path else (data or b""))
    with Image.open(path if path else io.BytesIO(data or b"")) as im:
        return int(im.width), int(im.height)


def decode_data_uri(src: str, max_bytes: int = 2 * 1024 * 1024) -> bytes | None:
    if not src.startswith("data:image/") or ";base64," not in src:
        return None
    payload = src.split(";base64,", 1)[1]
    if len(payload) > max_bytes * 4 // 3 + 4:
        return None
    try:
        return base64.b64decode(payload, validate=True)
    except (binascii.Error, ValueError):
        return None


class MappingAssetResolver:
    """Resolves asset ids to local files from a dict; supports ``data:`` URIs; no network."""

    def __init__(self, mapping: dict[str, str] | None = None) -> None:
        self.mapping = dict(mapping or {})
        self._refs: dict[str, ImageRef] = {}

    def image(self, asset_id: str) -> ImageRef | None:
        if asset_id in self._refs:
            return self._refs[asset_id]
        path = self.mapping.get(asset_id)
        if not path or not Path(path).exists():
            return None
        w, h = image_size(path=path)
        ref = ImageRef(key=asset_id, path=path, width=w, height=h, vector=looks_like_svg(path=path))
        self._refs[asset_id] = ref
        return ref

    def fetch(self, src: str) -> ImageRef | None:
        data = decode_data_uri(src)
        if data is None:
            return None
        try:
            w, h = image_size(data=data)
        except Exception:
            return None
        import hashlib

        return ImageRef(key="data:" + hashlib.sha256(data).hexdigest()[:24], data=data, width=w, height=h, vector=looks_like_svg(data=data))


def bundled_font_files() -> Iterable[Path]:
    return sorted(BUNDLED_FONTS_DIR.glob("*/*.ttf"))
