"""Helpers for tests, golden fixtures and benchmarks: a FontLibrary over the bundled OFL fonts."""

from __future__ import annotations

import json
from pathlib import Path

from .fontprep import prepare_font
from .providers import FontFace, FontLibrary, bundled_font_files


def prepare_bundled_fonts(cache_dir: str | Path) -> list[FontFace]:
    """Prepare bundled fonts (pdf.ttf + metrics.json) into ``cache_dir`` once; return faces.

    Face key = ``{family}-{weight}{-italic}`` lowercased, e.g. ``inter-400``, ``inter-700``.
    """
    cache = Path(cache_dir)
    faces: list[FontFace] = []
    for src in bundled_font_files():
        out = cache / src.stem
        metrics_path = out / "metrics.json"
        pdf_path = out / "pdf.ttf"
        if not metrics_path.exists() or not pdf_path.exists() or metrics_path.stat().st_mtime < src.stat().st_mtime:
            prepared = prepare_font(src.read_bytes())
            out.mkdir(parents=True, exist_ok=True)
            pdf_path.write_bytes(prepared.pdf_ttf)
            (out / "web.woff2").write_bytes(prepared.woff2)
            metrics_path.write_text(json.dumps(prepared.metrics, separators=(",", ":")), encoding="utf-8")
        meta = json.loads(metrics_path.read_text(encoding="utf-8"))
        key = f"{meta['family']}-{meta['weight']}{'-italic' if meta['style'] == 'italic' else ''}".lower()
        faces.append(
            FontFace(
                key=key,
                family=meta["family"],
                weight=int(meta["weight"]),
                style=meta["style"],
                metrics_path=str(metrics_path),
                pdf_path=str(pdf_path),
                ids=(key,),
            )
        )
    return faces


def bundled_library(cache_dir: str | Path) -> FontLibrary:
    return FontLibrary(prepare_bundled_fonts(cache_dir))
