#!/usr/bin/env python3
"""Download Google fonts as ttf and measure candidate text with PIL."""
import io
import os
import re
import sys
import urllib.request

import numpy as np
from PIL import Image, ImageDraw, ImageFont
from fontTools.ttLib import TTFont

UA = ("Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 "
      "(KHTML, like Gecko) Chrome/124.0 Safari/537.36")
CACHE = os.path.join(os.path.dirname(os.path.abspath(__file__)), "fonts")
os.makedirs(CACHE, exist_ok=True)


def fam_param(fam, wght):
    return fam.replace(" ", "+") + ":wght@" + str(wght)


def get_font(fam, wght=400, wdth=None):
    key = f"{fam.replace(' ', '_')}_{wght}_{wdth or ''}"
    path = os.path.join(CACHE, key + ".ttf")
    if os.path.exists(path):
        return path
    fams = fam_param(fam, wght)
    url = ("https://fonts.googleapis.com/css2?family=" + fams + "&display=block")
    req = urllib.request.Request(url, headers={"User-Agent": UA})
    css = urllib.request.urlopen(req, timeout=30).read().decode()
    urls = re.findall(r"url\((https://[^)]+\.woff2)\)", css)
    if not urls:
        raise RuntimeError("no font url for " + fam + "\n" + css[:400])
    for url0 in urls:
        data = urllib.request.urlopen(url0, timeout=30).read()
        f = TTFont(io.BytesIO(data))
        if 0x41 in f.getBestCmap():
            f.flavor = None
            f.save(path)
            return path
    raise RuntimeError("no latin subset for " + fam)


def render_row(fam, wght, text, cap=354, wdth=None, stroke=0):
    path = get_font(fam, wght, wdth)
    f = TTFont(path)
    # find font size giving requested cap, using 'H'
    probe = ImageFont.truetype(path, 400)
    if wdth is not None:
        try:
            probe.set_variation_by_axes([wdth] if len(probe.get_variation_axes()) == 1 else None)
        except Exception:
            pass
    # measure cap of H at 400
    img = Image.new("L", (1200, 700), 0)
    d = ImageDraw.Draw(img)
    d.text((50, 50), "H", font=probe, fill=255, stroke_width=stroke)
    a = np.asarray(img)
    ys = np.where(a.max(1) > 100)[0]
    cap400 = ys.max() - ys.min() + 1
    size = int(round(400 * cap / cap400))
    font = ImageFont.truetype(path, size)
    if wdth is not None:
        try:
            axes = font.get_variation_axes()
            vals = []
            for ax in axes:
                tag = ax["name"].decode() if isinstance(ax["name"], bytes) else str(ax["name"])
                # PIL tags: 'Weight', 'Width'
                if "eight" in tag:
                    vals.append(wght)
                elif "idth" in tag:
                    vals.append(wdth)
                else:
                    vals.append(ax["default"])
            if vals:
                font.set_variation_by_axes(vals)
        except Exception as e:
            print("var fail", e)
    img = Image.new("L", (3000, 900), 0)
    d = ImageDraw.Draw(img)
    d.text((60, 120), text, font=font, fill=255, stroke_width=stroke,
           stroke_fill=255)
    a = np.asarray(img)
    m = a > 128
    ys, xs = np.where(m)
    bbox = (xs.min(), ys.min(), xs.max(), ys.max())
    # stems: run lengths in a row through middle
    midy = (ys.min() + ys.max()) // 2
    row = m[midy]
    runs = []
    s = None
    for i, v in enumerate(row):
        if v and s is None:
            s = i
        if not v and s is not None:
            runs.append(i - s)
            s = None
    return {
        "fam": fam, "wght": wght, "wdth": wdth, "size": size,
        "ink": (bbox[2] - bbox[0] + 1, bbox[3] - bbox[1] + 1),
        "bbox": bbox, "runs": runs,
        "img": img, "mask": m,
    }


if __name__ == "__main__":
    text = sys.argv[1] if len(sys.argv) > 1 else "SKIN."
    specs = sys.argv[2].split(",") if len(sys.argv) > 2 else ["Archivo Black:400"]
    for spec in specs:
        bits = spec.split(":")
        fam, wght = bits[0], int(bits[1]) if len(bits) > 1 else 400
        wdth = float(bits[2]) if len(bits) > 2 else None
        try:
            r = render_row(fam, wght, text, wdth=wdth)
            print(f"{fam:24s} {wght} wdth={wdth} size={r['size']:4d} "
                  f"ink={r['ink']} runs={r['runs']}")
        except Exception as e:
            print(f"{fam}: FAIL {e}")
