#!/usr/bin/env python3
"""Inline Plus Jakarta Sans into the embeddable widget.

The widget runs on customers' websites, so it cannot assume the host page has
the font, and it should not add a webfont request there. Fetching from Google
would put a third-party dependency on someone else's page load and send every
visitor's IP to Google. Serving the font from our own origin avoids the privacy
problem but not the rest: it is still a second request, it is still blockable,
and because fonts are CORS-restricted it silently falls back to system-ui the
moment the Access-Control-Allow-Origin header goes missing. The font is
inlined instead — it ships inside the already-downloaded widget script.

One variable file, not several static weights. The widget uses 400, 500 and
600; as static latin woff2 those are 36,316 bytes, while the latin variable
file is 27,348 and covers the whole 200-800 axis. Smaller, and no weight has to
be mapped onto a neighbour.

Latin subset, upright only. The widget renders no italic and no other script.

    python3 scripts/build-widget-font.py
"""

from __future__ import annotations

import base64
from pathlib import Path

WEB = Path(__file__).resolve().parent.parent
SOURCE = (
    WEB
    / "node_modules"
    / "@fontsource-variable"
    / "plus-jakarta-sans"
    / "files"
    / "plus-jakarta-sans-latin-wght-normal.woff2"
)
WIDGET = WEB / "public" / "scripts" / "rag-agent-widget.js"

BEGIN = "  /* BEGIN GENERATED FONT DATA"
END = "  /* END GENERATED FONT DATA */"


def main() -> None:
    if not SOURCE.exists():
        raise SystemExit(
            f"missing {SOURCE}\n"
            "  Run: cd apps/web && npm install --save-dev @fontsource-variable/plus-jakarta-sans"
        )

    raw = SOURCE.read_bytes()
    encoded = base64.b64encode(raw).decode("ascii")

    block = (
        f"{BEGIN} — regenerate with: python3 scripts/build-widget-font.py */\n"
        "  // Plus Jakarta Sans, latin subset, variable weight 200-800, upright.\n"
        f"  // {len(raw)} bytes of woff2, {len(encoded)} bytes of base64.\n"
        "  // Inlined, not fetched: no third-party request on a customer's page,\n"
        "  // no visitor IP sent to Google, and no CORS header to silently break.\n"
        "  var FONT_FAMILY = 'Plus Jakarta Sans';\n"
        "  var FONT_WEIGHT_RANGE = '200 800';\n"
        f"  var FONT_SRC = 'url(data:font/woff2;base64,{encoded}) format(\"woff2\")';\n"
        f"{END}"
    )

    text = WIDGET.read_text(encoding="utf-8")
    start = text.find(BEGIN)
    stop = text.find(END)
    if start == -1 or stop == -1:
        raise SystemExit(f"generated-font markers not found in {WIDGET}")

    WIDGET.write_text(text[:start] + block + text[stop + len(END):], encoding="utf-8")
    print(
        f"inlined {SOURCE.name} into {WIDGET.relative_to(WEB)} — "
        f"{len(raw)} B woff2 -> {len(encoded)} B base64"
    )


if __name__ == "__main__":
    main()
