"""Runtime font metrics loaded from ``metrics.json`` (format: ``spec/text-layout.md`` section 3).

Kerning lookup semantics (same in the TS implementation)::

    kern(a, b) = sum over lookups L of value(first subtable S in L that matches (a, b)), 0 if none
    pair subtable  {"t": "p", "v": {a: {b: value}}}           matches iff v[a][b] exists
    class subtable {"t": "c", "cov": [...], "c1", "c2", "m"}  matches iff a in cov;
                   value = m[c1.get(a, 0)][c2.get(b, 0)] (0 if the index is out of range)
"""

from __future__ import annotations

import json
from pathlib import Path
from typing import Any


class _PairSub:
    __slots__ = ("pairs",)

    def __init__(self, raw: dict[str, Any]) -> None:
        self.pairs = {int(a): {int(b): int(v) for b, v in row.items()} for a, row in raw["v"].items()}

    def match(self, a: int, b: int) -> int | None:
        row = self.pairs.get(a)
        if row is None:
            return None
        return row.get(b)


class _ClassSub:
    __slots__ = ("c1", "c2", "cov", "matrix")

    def __init__(self, raw: dict[str, Any]) -> None:
        self.cov = frozenset(int(c) for c in raw["cov"])
        self.c1 = {int(k): int(v) for k, v in raw["c1"].items()}
        self.c2 = {int(k): int(v) for k, v in raw["c2"].items()}
        self.matrix: list[list[int]] = raw["m"]

    def match(self, a: int, b: int) -> int | None:
        if a not in self.cov:
            return None
        k1 = self.c1.get(a, 0)
        k2 = self.c2.get(b, 0)
        if k1 >= len(self.matrix):
            return 0
        row = self.matrix[k1]
        return row[k2] if k2 < len(row) else 0


class FontMetrics:
    __slots__ = (
        "_kern_cache",
        "advances",
        "ascender",
        "cap_height",
        "descender",
        "family",
        "key",
        "line_gap",
        "lookups",
        "missing_advance",
        "style",
        "underline_position",
        "underline_thickness",
        "upm",
        "weight",
        "x_height",
    )

    def __init__(self, key: str, raw: dict[str, Any]) -> None:
        self.key = key
        self.family: str = raw.get("family", "")
        self.weight: int = int(raw.get("weight", 400))
        self.style: str = raw.get("style", "normal")
        self.upm = int(raw["unitsPerEm"])
        self.ascender = int(raw["ascender"])
        self.descender = int(raw["descender"])
        self.line_gap = int(raw.get("lineGap", 0))
        self.cap_height = int(raw.get("capHeight", 0))
        self.x_height = int(raw.get("xHeight", 0))
        self.underline_position = int(raw.get("underlinePosition", -self.upm // 10))
        self.underline_thickness = int(raw.get("underlineThickness", self.upm // 20))
        self.missing_advance = int(raw.get("missingAdvance", self.upm // 2))
        self.advances: dict[int, int] = {int(k): int(v) for k, v in raw["advances"].items()}
        self.lookups: list[list[_PairSub | _ClassSub]] = [
            [_PairSub(s) if s["t"] == "p" else _ClassSub(s) for s in lookup] for lookup in raw.get("kerning", [])
        ]
        self._kern_cache: dict[tuple[int, int], int] = {}

    @classmethod
    def from_file(cls, key: str, path: str | Path) -> FontMetrics:
        return cls(key, json.loads(Path(path).read_text(encoding="utf-8")))

    def has(self, cp: int) -> bool:
        return cp in self.advances

    def advance(self, cp: int) -> int:
        return self.advances.get(cp, self.missing_advance)

    def kern(self, a: int, b: int) -> int:
        key = (a, b)
        cached = self._kern_cache.get(key)
        if cached is not None:
            return cached
        total = 0
        for lookup in self.lookups:
            for sub in lookup:
                v = sub.match(a, b)
                if v is not None:
                    total += v
                    break
        self._kern_cache[key] = total
        return total
