import os, re, sys, json, urllib.request

UA = "Mozilla/4.0"
OUT = "work/fonts"
os.makedirs(OUT, exist_ok=True)


def get(url, ua=UA):
    req = urllib.request.Request(url, headers={"User-Agent": ua})
    return urllib.request.urlopen(req, timeout=60).read()


def fetch(family, weight, width=None):
    name = family.replace(" ", "+")
    if width:
        spec = f"wdth,wght@{width},{weight}"
    else:
        spec = f"wght@{weight}"
    url = f"https://fonts.googleapis.com/css2?family={name}:{spec}&display=block"
    css = get(url).decode()
    urls = re.findall(r"url\((https://[^)]+\.ttf)\)", css)
    path = os.path.join(OUT, f"{family.replace(' ','_')}_{weight}_{width or 'na'}.ttf")
    if not urls:
        return None
    if not os.path.exists(path):
        open(path, "wb").write(get(urls[-1]))
    return path


if __name__ == "__main__":
    specs = json.loads(sys.argv[1])
    for s in specs:
        fam, wt = s[0], s[1]
        wd = s[2] if len(s) > 2 else None
        try:
            p = fetch(fam, wt, wd)
            print(fam, wt, wd, p)
        except Exception as e:
            print("FAIL", fam, wt, wd, e)
