#!/usr/bin/env python3
"""Generate Vanta's fonts_customization.xml: LineageOS's own file plus IBM Plex Sans.

A product has exactly one /product/etc/fonts_customization.xml, and LineageOS
ships it (packages/overlays/Lineage/fonts/etc). Android 17's Soong writes a Kati
install rule for every module, selected or not, so a second module at that path
kills the build ("overriding commands for target") and `overrides:` cannot
help. So there is no Vanta module: tools/fonts.sh copies this file over
Lineage's source and Lineage's own module installs it. Its content has to be
Lineage's families *plus* ours — dropping theirs would break every Lineage font
overlay still in the image. The file is built from the synced tree's copy so
the two cannot drift; `--check` fails if the committed file no longer equals
Lineage's current file + our block. A tree that fonts.sh already ran on reads
as Lineage's file again (our block is stripped first), so re-runs are clean.

Usage: tools/gen_fonts.py [--src TREE] [--check]
"""
import argparse
import os
import sys

HERE = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
OUT = os.path.join(HERE, "vendor/vanta/fonts/fonts_customization.xml")
UPSTREAM = "packages/overlays/Lineage/fonts/etc/fonts_customization.xml"
FAMILY = "ibm-plex-sans"
FILES = {"normal": "IBMPlexSans-VF.ttf", "italic": "IBMPlexSans-Italic-VF.ttf"}
WEIGHTS = [100, 200, 300, 400, 500, 600, 700]
ALIASES = {"regular": 400, "medium": 500, "bold": 700, "clock": 300}


def block():
    out = ["    <!-- Vanta: IBM Plex Sans (OFL-1.1), one variable file per style. -->",
           f'    <family customizationType="new-named-family" name="{FAMILY}">']
    for style, ttf in FILES.items():
        for w in WEIGHTS:
            out += [f'        <font weight="{w}" style="{style}">{ttf}',
                    f'            <axis tag="wght" stylevalue="{w}"/>',
                    "        </font>"]
    out.append("    </family>")
    out += [f'    <alias name="{FAMILY}-{n}" to="{FAMILY}" weight="{w}"/>' for n, w in ALIASES.items()]
    return "\n".join(out) + "\n"


def build(src):
    up = os.path.join(src, UPSTREAM)
    if not os.path.exists(up):
        raise SystemExit(f"gen_fonts: missing {up}")
    text = open(up, encoding="utf-8").read().replace(block(), "")
    end = "</fonts-modification>"
    if text.count(end) != 1:
        raise SystemExit(f"gen_fonts: anchor {end!r} not found exactly once in {UPSTREAM}")
    return text.replace(end, block() + end)


def main():
    ap = argparse.ArgumentParser()
    ap.add_argument("--src", default=os.path.join(HERE, "build/l24"))
    ap.add_argument("--check", action="store_true")
    a = ap.parse_args()
    want = build(a.src)
    have = open(OUT, encoding="utf-8").read() if os.path.exists(OUT) else None
    if a.check:
        print("gen_fonts: " + ("ok" if want == have else "DRIFT (re-run tools/gen_fonts.py)"))
        return 0 if want == have else 1
    open(OUT, "w", encoding="utf-8").write(want)
    print(f"gen_fonts: wrote {OUT}")
    return 0


if __name__ == "__main__":
    sys.exit(main())
