#!/usr/bin/env python3
"""Build locale-targeted variable WOFF2 slices with pyftsubset."""

from __future__ import annotations

import subprocess
import sys
from pathlib import Path

from fontTools.ttLib import TTFont

ROOT = Path(__file__).resolve().parent.parent
SUBSET_SPECS = ROOT / "subsets"
SUBSET_ORDER = ("vietnamese", "latin-ext", "latin-core")


def unicode_ranges(path: Path) -> list[str]:
    ranges = []
    for line in path.read_text().splitlines():
        line = line.split("#", 1)[0]
        ranges.extend(
            token.strip()
            for token in line.replace(",", " ").split()
            if token.strip()
        )
    return ranges


def subset_one(source: Path, output: Path, unicode_file: Path) -> None:
    command = [
        sys.executable,
        "-m",
        "fontTools.subset",
        str(source),
        f"--output-file={output}",
        f"--unicodes-file={unicode_file}",
        "--flavor=woff2",
        "--layout-features=*",
        "--glyph-names",
        "--symbol-cmap",
        "--legacy-cmap",
        "--notdef-glyph",
        "--notdef-outline",
        "--recommended-glyphs",
        "--name-IDs=*",
        "--name-legacy",
        "--name-languages=*",
        "--no-recalc-timestamp",
        "--canonical-order",
        "--prune-unicode-ranges",
        "--prune-codepage-ranges",
        "--recalc-average-width",
        "--recalc-max-context",
    ]
    subprocess.run(command, check=True)
    # pyftsubset preserves the source hhea extrema even when the glyph that
    # established them is absent from a slice. Recalculate all horizontal
    # header metrics so each standalone WOFF2 describes its own glyph set.
    font = TTFont(output, recalcTimestamp=False)
    font["hhea"].recalc(font)
    font.save(output)


def build_subsets(variable_paths: dict[str, Path], dist: Path):
    output_dir = dist / "subsets"
    output_dir.mkdir(parents=True, exist_ok=True)
    outputs = []
    css_blocks = [
        "/* Generated from subsets/*.txt by pipeline/build_subsets.py. */",
        "",
    ]

    for style in ("upright", "italic"):
        source = variable_paths[style]
        for subset_name in SUBSET_ORDER:
            unicode_file = SUBSET_SPECS / f"{subset_name}.txt"
            italic_infix = "-Italic" if style == "italic" else ""
            filename = f"PivotSans{italic_infix}-{subset_name}[wght].woff2"
            output = output_dir / filename
            subset_one(source, output, unicode_file)
            outputs.append(output)

            ranges = ", ".join(unicode_ranges(unicode_file))
            css_blocks.extend(
                [
                    "@font-face {",
                    '  font-family: "Pivot Sans";',
                    f"  font-style: {'italic' if style == 'italic' else 'normal'};",
                    "  font-weight: 300 700;",
                    "  font-display: swap;",
                    f'  src: url("subsets/{filename}") format("woff2-variations");',
                    f"  unicode-range: {ranges};",
                    "}",
                    "",
                ]
            )

    css_path = dist / "pivot-sans-subsets.css"
    css_path.write_text("\n".join(css_blocks))
    for output in outputs:
        print(
            f"built {output.relative_to(ROOT)} "
            f"({output.stat().st_size / 1024:.1f} KiB)"
        )
    print(f"built {css_path.relative_to(ROOT)}")
    return outputs, css_path


def main() -> None:
    variable_paths = {
        "upright": ROOT / "dist" / "PivotSans[wght].ttf",
        "italic": ROOT / "dist" / "PivotSans-Italic[wght].ttf",
    }
    build_subsets(variable_paths, ROOT / "dist")


if __name__ == "__main__":
    main()
