"""
setup_fonts.py — Descarga las fuentes Google Fonts necesarias para Kings & Queens flyers.
Solo usa stdlib (urllib.request). Sin dependencias extra.

Uso:
    wsl python3 projects/kings-and-queens/scripts/setup_fonts.py
"""

import sys
import os
import urllib.request
import urllib.error
from pathlib import Path

FONTS_DIR = Path(__file__).parent.parent / "assets" / "fonts"

# Fuentes a descargar: (filename_destino, google_fonts_family, weight)
FONT_SPECS = [
    ("FredokaOne-Regular.ttf",  "Fredoka+One",  "400"),
    ("Nunito-SemiBold.ttf",     "Nunito",        "600"),
    ("Nunito-Regular.ttf",      "Nunito",        "400"),
    ("Pacifico-Regular.ttf",    "Pacifico",      "400"),
]


def get_font_url(family: str, weight: str) -> str:
    """
    Obtiene la URL del TTF consultando la API de Google Fonts CSS.
    Usa el header User-Agent de Android para recibir TTF (no WOFF2).
    """
    import re
    api_url = f"https://fonts.googleapis.com/css?family={family}:wght@{weight}"
    req = urllib.request.Request(
        api_url,
        headers={"User-Agent": "Mozilla/5.0 (Android 11; Mobile)"}
    )
    with urllib.request.urlopen(req, timeout=15) as resp:
        css = resp.read().decode("utf-8")
    match = re.search(r"src:\s+url\(([^)]+\.ttf)\)", css)
    if not match:
        # Intentar con formato alternativo
        match = re.search(r"url\(([^)]+\.ttf)\)", css)
    if not match:
        raise ValueError(f"No se encontró URL TTF para {family}:{weight}")
    return match.group(1)


def verify_font(path: Path) -> bool:
    """Verifica que el archivo sea un TTF válido cargándolo con Pillow."""
    try:
        from PIL import ImageFont
        ImageFont.truetype(str(path), size=20)
        return True
    except Exception as e:
        print(f"  ERROR al verificar: {e}")
        return False


def download_font(name: str, family: str, weight: str) -> bool:
    dest = FONTS_DIR / name
    if dest.exists():
        print(f"  {name} — ya existe, saltando.")
        return True

    print(f"  Resolviendo URL para {name}...", end=" ", flush=True)
    try:
        url = get_font_url(family, weight)
        print(f"OK. Descargando...", end=" ", flush=True)
    except Exception as e:
        print(f"\n  ERROR al obtener URL: {e}")
        return False

    try:
        req = urllib.request.Request(url, headers={"User-Agent": "Mozilla/5.0"})
        with urllib.request.urlopen(req, timeout=30) as response:
            data = response.read()
        dest.write_bytes(data)
        print(f"{len(data) // 1024} KB.", end=" ", flush=True)
    except urllib.error.URLError as e:
        print(f"\n  ERROR de red: {e}")
        return False

    if verify_font(dest):
        print("OK")
        return True
    else:
        dest.unlink(missing_ok=True)
        return False


def main():
    print("=== Kings & Queens — Setup de Fuentes ===\n")

    FONTS_DIR.mkdir(parents=True, exist_ok=True)
    print(f"Directorio de fuentes: {FONTS_DIR}\n")

    errors = []
    for name, family, weight in FONT_SPECS:
        result = download_font(name, family, weight)
        if not result:
            errors.append(name)

    print()
    if errors:
        print(f"FALLARON {len(errors)} fuente(s): {', '.join(errors)}")
        print("Intentá correr el script de nuevo o descargalas manualmente desde fonts.google.com")
        sys.exit(1)
    else:
        print(f"Todas las fuentes están listas en {FONTS_DIR}")
        sys.exit(0)


if __name__ == "__main__":
    main()
