#!/usr/bin/env bash
set -euo pipefail

# --- Einstellungen ---
SUBSET="latin"        # für DE/EN am kleinsten; bei Bedarf "latin-ext"
WEIGHT="400"
DISPLAY="swap"

# Moderner UA erzwingt woff2 im Google-Fonts CSS
UA="Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/123 Safari/537.36"

# Familienliste (Leerzeichen -> '+')
FAMILIES=(
"Abril+Fatface"
"Alegreya"
"Alfa+Slab+One"
"Almendra"
"Amatic+SC"
"Andika"
"Architects+Daughter"
"Audiowide"
"Averia+Libre"
"Bebas+Neue"
"Black+Ops+One"
"Caveat"
"Cinzel+Decorative"
"Courgette"
"Dancing+Script"
"Exo"
"Fjalla+One"
"Germania+One"
"Glass+Antiqua"
"Gloria+Hallelujah"
"Great+Vibes"
"Holtwood+One+SC"
"Indie+Flower"
"Italiana"
"Jost"
"Kaushan+Script"
"Lato"
"Metal+Mania"
"Montserrat"
"Neucha"
"Noto+Sans"
"Open+Sans"
"Orbitron"
"Oswald"
"Pacifico"
"Permanent+Marker"
"Philosopher"
"Playfair+Display"
"Poppins"
"Press+Start+2P"
"Questrial"
"Quicksand"
"Rajdhani"
"Raleway"
"Righteous"
"Roboto"
"Sacramento"
"Satisfy"
"Space+Mono"
"Spectral"
"Staatliches"
"Stint+Ultra+Condensed"
"Syncopate"
"Ultra"
"Unica+One"
"Work+Sans"
"Yellowtail"
)

# --- Output vorbereiten ---
: > font-src-urls.csv
echo "family,woff2_url" >> font-src-urls.csv
: > fonts.css

echo "Hole woff2-URLs (Subset: $SUBSET, Weight: $WEIGHT) …" >&2

for FAMILY in "${FAMILIES[@]}"; do
  API_URL="https://fonts.googleapis.com/css2?family=${FAMILY}:wght@${WEIGHT}&display=${DISPLAY}"
  CSS="$(curl -s -H "User-Agent: ${UA}" "${API_URL}")"

  # bevorzugt den /* latin */-Block
  URL="$(printf "%s\n" "$CSS" \
    | awk '/\/\* '"$SUBSET"' \*\//,/\}/' \
    | grep -o 'https://fonts.gstatic.com[^)]*\.woff2' \
    | head -n1 || true)"

  # Fallback: erste woff2-URL überhaupt
  if [[ -z "${URL}" ]]; then
    URL="$(printf "%s\n" "$CSS" \
      | grep -o 'https://fonts.gstatic.com[^)]*\.woff2' \
      | head -n1 || true)"
  fi

  if [[ -z "${URL}" ]]; then
    echo "WARN: Keine woff2-URL für ${FAMILY} gefunden" >&2
    continue
  fi

  # CSV-Zeile
  echo "${FAMILY},${URL}" >> font-src-urls.csv

  # @font-face Snippet
  CSS_FAMILY="${FAMILY//+/ }"
  cat >> fonts.css <<CSS
@font-face {
  font-family: '${CSS_FAMILY}';
  font-style: normal;
  font-weight: ${WEIGHT};
  font-display: ${DISPLAY};
  src: url('${URL}') format('woff2');
  /* subset: ${SUBSET} (aus Google Fonts CSS v2) */
}
CSS

done

echo "Fertig. Siehe font-src-urls.csv und fonts.css" >&2
