"""Font preparation at upload time (TZ 2.6.4). The only engine module that imports fontTools.

``prepare_font(data)`` validates a TTF/OTF/WOFF/WOFF2 file, converts CFF outlines to TrueType (cu2qu),
normalises and subsets it to ``pdf.ttf`` for ReportLab, extracts ``metrics.json`` (advances + kerning,
format described in ``spec/text-layout.md``) and builds ``web.woff2`` from the same ``pdf.ttf``.
"""

from __future__ import annotations

import io
from dataclasses import dataclass, field
from typing import Any

from fontTools.pens.cu2quPen import Cu2QuPen
from fontTools.pens.ttGlyphPen import TTGlyphPen
from fontTools.subset import Options, Subsetter
from fontTools.ttLib import TTFont, newTable

from .errors import RenderError

METRICS_FORMAT = 1
MAX_FONT_BYTES = 20 * 1024 * 1024

# Default coverage (TZ 2.6.4 p.2.4): Basic Latin, Latin-1, Latin Ext-A, Cyrillic (+Supplement),
# General Punctuation, Currency, Letterlike, Number Forms, Arrows, Math Operators.
DEFAULT_RANGES: tuple[tuple[int, int], ...] = (
    (0x0020, 0x007E),
    (0x00A0, 0x00FF),
    (0x0100, 0x017F),
    (0x0370, 0x03FF),
    (0x0400, 0x04FF),
    (0x0500, 0x052F),
    (0x2000, 0x206F),
    (0x20A0, 0x20CF),
    (0x2100, 0x214F),
    (0x2150, 0x218F),
    (0x2190, 0x21FF),
    (0x2200, 0x22FF),
    (0x25A0, 0x25FF),
    (0x2600, 0x26FF),
)

_HINTING_TABLES = ("fpgm", "prep", "cvt ", "hdmx", "VDMX", "LTSH", "DSIG", "GSUB", "gasp")
_KERN_SCRIPTS = ("DFLT", "latn", "cyrl")


@dataclass
class PreparedFont:
    pdf_ttf: bytes
    woff2: bytes
    metrics: dict[str, Any]
    info: dict[str, Any] = field(default_factory=dict)


def _detect_format(data: bytes) -> str:
    head = data[:4]
    if head == b"wOF2":
        return "woff2"
    if head == b"wOFF":
        return "woff"
    if head == b"OTTO":
        return "otf"
    if head in (b"\x00\x01\x00\x00", b"true"):
        return "ttf"
    raise RenderError("FONT_INVALID", "Unsupported font signature")


def _convert_cff_to_ttf(font: TTFont, max_err: float = 1.0) -> None:
    """CFF -> glyf via cu2qu, keeping hmtx/cmap/kern/GPOS/OS2/hhea untouched (identical advances)."""
    glyph_order = font.getGlyphOrder()
    glyph_set = font.getGlyphSet()
    glyf = newTable("glyf")
    glyf.glyphOrder = glyph_order
    glyf.glyphs = {}
    for name in glyph_order:
        pen = TTGlyphPen(glyph_set)
        glyph_set[name].draw(Cu2QuPen(pen, max_err, reverse_direction=True))
        glyf.glyphs[name] = pen.glyph()
    font["glyf"] = glyf
    font["loca"] = newTable("loca")
    maxp = newTable("maxp")
    maxp.tableVersion = 0x00010000
    for attr in (
        "maxZones",
        "maxTwilightPoints",
        "maxStorage",
        "maxFunctionDefs",
        "maxInstructionDefs",
        "maxStackElements",
        "maxSizeOfInstructions",
        "maxComponentElements",
    ):
        setattr(maxp, attr, 0)
    maxp.maxZones = 1
    maxp.maxComponentDepth = 0
    maxp.numGlyphs = len(glyph_order)
    for attr in ("maxPoints", "maxContours", "maxCompositePoints", "maxCompositeContours"):
        setattr(maxp, attr, 0)
    font["maxp"] = maxp
    post = font["post"]
    post.formatType = 2.0
    post.extraNames = []
    post.mapping = {}
    post.glyphOrder = glyph_order
    for tag in ("CFF ", "CFF2", "VORG"):
        if tag in font:
            del font[tag]
    font.sfntVersion = "\x00\x01\x00\x00"
    font.recalcBBoxes = True


def _name(font: TTFont, *ids: int) -> str:
    table = font["name"]
    for name_id in ids:
        rec = table.getDebugName(name_id)
        if rec:
            return str(rec)
    return ""


def _subset(font: TTFont, ranges: tuple[tuple[int, int], ...]) -> None:
    unicodes = [cp for lo, hi in ranges for cp in range(lo, hi + 1)]
    opts = Options()
    opts.layout_features = ["kern"]
    opts.hinting = False
    opts.notdef_outline = True
    opts.notdef_glyph = True
    opts.name_IDs = ["*"]
    opts.name_languages = ["*"]
    opts.glyph_names = False
    opts.legacy_kern = True
    opts.drop_tables = [*opts.drop_tables, *_HINTING_TABLES]
    sub = Subsetter(options=opts)
    sub.populate(unicodes=unicodes)
    sub.subset(font)


def _reverse_cmap(font: TTFont) -> tuple[dict[int, str], dict[str, list[int]]]:
    cmap = font.getBestCmap() or {}
    rev: dict[str, list[int]] = {}
    for cp, glyph in sorted(cmap.items()):
        rev.setdefault(glyph, []).append(cp)
    return cmap, rev


def _value_x_advance(value: Any) -> int:
    if value is None:
        return 0
    return int(getattr(value, "XAdvance", 0) or 0)


def _gpos_kerning(font: TTFont, rev: dict[str, list[int]]) -> list[list[dict[str, Any]]] | None:
    if "GPOS" not in font:
        return None
    gpos = font["GPOS"].table
    if not gpos.FeatureList or not gpos.LookupList or not gpos.ScriptList:
        return None
    feature_idx: set[int] = set()
    for sr in gpos.ScriptList.ScriptRecord:
        if sr.ScriptTag not in _KERN_SCRIPTS or sr.Script.DefaultLangSys is None:
            continue
        for fi in sr.Script.DefaultLangSys.FeatureIndex:
            if gpos.FeatureList.FeatureRecord[fi].FeatureTag == "kern":
                feature_idx.add(fi)
    lookup_idx: set[int] = set()
    for fi in feature_idx:
        lookup_idx.update(gpos.FeatureList.FeatureRecord[fi].Feature.LookupListIndex)
    if not lookup_idx:
        return None

    def cps(glyph: str) -> list[int]:
        return rev.get(glyph, [])

    lookups: list[list[dict[str, Any]]] = []
    for li in sorted(lookup_idx):
        lookup = gpos.LookupList.Lookup[li]
        subtables = list(lookup.SubTable)
        ltype = lookup.LookupType
        if ltype == 9:
            ltype = subtables[0].ExtensionLookupType if subtables else 0
            subtables = [st.ExtSubTable for st in subtables]
        if ltype != 2:
            continue
        out_subtables: list[dict[str, Any]] = []
        for st in subtables:
            if st.Format == 1:
                pairs: dict[str, dict[str, int]] = {}
                for i, g1 in enumerate(st.Coverage.glyphs):
                    first_cps = cps(g1)
                    if not first_cps:
                        continue
                    row: dict[str, int] = {}
                    for pvr in st.PairSet[i].PairValueRecord:
                        v = _value_x_advance(pvr.Value1)
                        for cp2 in cps(pvr.SecondGlyph):
                            row.setdefault(str(cp2), v)
                    if row:
                        for cp1 in first_cps:
                            pairs[str(cp1)] = row
                if pairs:
                    out_subtables.append({"t": "p", "v": pairs})
            elif st.Format == 2:
                cov = [cp for g in st.Coverage.glyphs for cp in cps(g)]
                if not cov:
                    continue
                cd1 = st.ClassDef1.classDefs if st.ClassDef1 else {}
                cd2 = st.ClassDef2.classDefs if st.ClassDef2 else {}
                c1 = {str(cp): k for g, k in cd1.items() if k for cp in cps(g)}
                c2 = {str(cp): k for g, k in cd2.items() if k for cp in cps(g)}
                matrix = [[_value_x_advance(c2r.Value1) for c2r in c1r.Class2Record] for c1r in st.Class1Record]
                if not any(any(r) for r in matrix):
                    continue
                out_subtables.append({"t": "c", "cov": sorted(cov), "c1": c1, "c2": c2, "m": matrix})
        if out_subtables:
            lookups.append(out_subtables)
    return lookups or None


def _legacy_kerning(font: TTFont, rev: dict[str, list[int]]) -> list[list[dict[str, Any]]] | None:
    if "kern" not in font:
        return None
    pairs: dict[str, dict[str, int]] = {}
    for table in font["kern"].kernTables:
        if getattr(table, "format", 0) != 0:
            continue
        for (g1, g2), v in table.kernTable.items():
            for cp1 in rev.get(g1, []):
                for cp2 in rev.get(g2, []):
                    pairs.setdefault(str(cp1), {}).setdefault(str(cp2), int(v))
    return [[{"t": "p", "v": pairs}]] if pairs else None


def extract_metrics(font: TTFont) -> dict[str, Any]:
    cmap, rev = _reverse_cmap(font)
    hmtx = font["hmtx"].metrics
    head = font["head"]
    hhea = font["hhea"]
    os2 = font.get("OS/2", None)
    use_typo = bool(os2 is not None and os2.fsSelection & (1 << 7))
    if use_typo and os2 is not None:
        asc, desc, gap = os2.sTypoAscender, os2.sTypoDescender, os2.sTypoLineGap
    else:
        asc, desc, gap = hhea.ascent, hhea.descent, hhea.lineGap
    advances = {str(cp): int(hmtx[g][0]) for cp, g in sorted(cmap.items()) if g in hmtx}
    notdef = font.getGlyphOrder()[0]
    kern = _gpos_kerning(font, rev) or _legacy_kerning(font, rev) or []
    post = font["post"]
    return {
        "format": METRICS_FORMAT,
        "family": _name(font, 16, 1),
        "subfamily": _name(font, 17, 2),
        "postscriptName": _name(font, 6),
        "weight": int(os2.usWeightClass) if os2 is not None else 400,
        "style": "italic" if (os2 is not None and os2.fsSelection & 1) or head.macStyle & 2 else "normal",
        "unitsPerEm": int(head.unitsPerEm),
        "ascender": int(asc),
        "descender": int(desc),
        "lineGap": int(gap),
        "capHeight": int(getattr(os2, "sCapHeight", 0) or 0) if os2 is not None else 0,
        "xHeight": int(getattr(os2, "sxHeight", 0) or 0) if os2 is not None else 0,
        "underlinePosition": int(post.underlinePosition),
        "underlineThickness": int(post.underlineThickness),
        "missingAdvance": int(hmtx[notdef][0]) if notdef in hmtx else int(head.unitsPerEm // 2),
        "advances": advances,
        "kerning": kern,
    }


def prepare_font(data: bytes, ranges: tuple[tuple[int, int], ...] | None = DEFAULT_RANGES) -> PreparedFont:
    if len(data) > MAX_FONT_BYTES:
        raise RenderError("FONT_TOO_LARGE", "Font file exceeds 20 MB")
    fmt = _detect_format(data)
    try:
        font = TTFont(io.BytesIO(data), lazy=False)
    except Exception as exc:  # fontTools raises many exception types on corrupt data
        raise RenderError("FONT_INVALID", f"Cannot parse font: {exc}") from exc
    for tag in ("head", "hhea", "name", "cmap", "hmtx", "post"):
        if tag not in font:
            raise RenderError("FONT_INVALID", f"Missing required table {tag!r}")
    if "fvar" in font:
        raise RenderError("FONT_UNSUPPORTED", "Variable fonts are not supported in v1; upload a static instance")
    if "CFF2" in font:
        raise RenderError("FONT_UNSUPPORTED", "CFF2 fonts are not supported in v1")
    os2 = font.get("OS/2", None)
    fs_type = int(os2.fsType) if os2 is not None else 0
    embeddable = fs_type & 15 != 2
    if not embeddable:
        raise RenderError("FONT_NOT_EMBEDDABLE", "Font license (OS/2 fsType) forbids embedding")
    font.flavor = None
    converted = False
    if "CFF " in font:
        try:
            _convert_cff_to_ttf(font)
        except Exception as exc:
            raise RenderError("FONT_CONVERSION_FAILED", f"CFF->TTF conversion failed: {exc}") from exc
        converted = True
    if ranges:
        _subset(font, ranges)
    else:
        for tag in _HINTING_TABLES:
            if tag in font:
                del font[tag]
    buf = io.BytesIO()
    font.save(buf)
    pdf_ttf = buf.getvalue()
    # Re-parse the produced file: metrics come from exactly what ReportLab and the editor will use.
    final = TTFont(io.BytesIO(pdf_ttf))
    metrics = extract_metrics(final)
    final.flavor = "woff2"
    wbuf = io.BytesIO()
    final.save(wbuf)
    info = {
        "format": fmt,
        "converted": converted,
        "embeddable": embeddable,
        "family": metrics["family"],
        "weight": metrics["weight"],
        "style": metrics["style"],
        "postscript_name": metrics["postscriptName"],
        "units_per_em": metrics["unitsPerEm"],
        "ascender": metrics["ascender"],
        "descender": metrics["descender"],
        "line_gap": metrics["lineGap"],
        "cap_height": metrics["capHeight"],
        "x_height": metrics["xHeight"],
        "glyph_count": len(final.getGlyphOrder()),
        "unicode_ranges": _coverage_summary(metrics["advances"]),
    }
    return PreparedFont(pdf_ttf=pdf_ttf, woff2=wbuf.getvalue(), metrics=metrics, info=info)


def _coverage_summary(advances: dict[str, int]) -> dict[str, bool]:
    cps = {int(k) for k in advances}
    return {
        "latin": all(cp in cps for cp in range(0x41, 0x5B)),
        "cyrillic": all(cp in cps for cp in range(0x410, 0x450)),
    }
