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

UA="Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/123 Safari/537.36"
DISPLAY="swap"
WEIGHT="400"

# Paare: Google-Fontname (URL-Form) | CSS-Fontname (CamelCase wie in deinen Utilities)
readarray -t FONTS <<'EOF'
Abril+Fatface|AbrilFatface
Alegreya|Alegreya
Alfa+Slab+One|AlfaSlabOne
Almendra|Almendra
Amatic+SC|AmaticSc
Andika|Andika
Architects+Daughter|ArchitectsDaughter
Audiowide|Audiowide
Averia+Libre|AveriaLibre
Bebas+Neue|BebasNeue
Black+Ops+One|BlackOpsOne
Caveat|Caveat
Cinzel+Decorative|CinzelDecorative
Courgette|Courgette
Dancing+Script|DancingScript
Exo|Exo
Fjalla+One|FjallaOne
Germania+One|GermaniaOne
Glass+Antiqua|GlassAntiqua
Gloria+Hallelujah|GloriaHallelujah
Great+Vibes|GreatVibes
Holtwood+One+SC|HoltwoodOneSc
Indie+Flower|IndieFlower
Italiana|Italiana
Jost|Jost
Kaushan+Script|KaushanScript
Lato|Lato
Metal+Mania|MetalMania
Montserrat|Montserrat
Neucha|Neucha
Noto+Sans|NotoSans
Open+Sans|OpenSans
Orbitron|Orbitron
Oswald|Oswald
Pacifico|Pacifico
Permanent+Marker|PermanentMarker
Philosopher|Philosopher
Playfair+Display|PlayfairDisplay
Poppins|Poppins
Press+Start+2P|PressStart2P
Questrial|Questrial
Quicksand|Quicksand
Rajdhani|Rajdhani
Raleway|Raleway
Righteous|Righteous
Roboto|Roboto
Sacramento|Sacramento
Satisfy|Satisfy
Space+Mono|SpaceMono
Spectral|Spectral
Staatliches|Staatliches
Stint+Ultra+Condensed|StintUltraCondensed
Syncopate|Syncopate
Ultra|Ultra
Unica+One|UnicaOne
Work+Sans|WorkSans
Yellowtail|Yellowtail
EOF

for line in "${FONTS[@]}"; do
  GF="${line%%|*}"
  CSS_FAMILY="${line##*|}"

  API_URL="https://fonts.googleapis.com/css2?family=${GF}:wght@${WEIGHT}&display=${DISPLAY}"
  CSS="$(curl -s -H "User-Agent: ${UA}" --compressed "$API_URL")"

  # Bevorzugt den /* latin */-Block, sonst den ersten @font-face mit font-style: normal
  BLOCK="$(awk '/\/\* latin \*\//,/\}/' <<<"$CSS")"
  if [[ -z "$BLOCK" ]]; then
    BLOCK="$(awk -v RS='}' '/@font-face/ && /font-style:[[:space:]]*normal/ {print $0 RS; exit}' <<<"$CSS")"
  fi

  SRC="$(grep -o 'https://fonts\.gstatic\.com[^)]*\.woff2' <<<"$BLOCK" | head -n1 || true)"
  URANGE="$(sed -n 's/^[[:space:]]*unicode-range:[[:space:]]*\(.*\);/\1/p' <<<"$BLOCK" || true)"

  if [[ -z "$SRC" ]]; then
    echo "/* WARN: no woff2 for ${GF} */" >&2
    continue
  fi

  cat <<CSSBLOCK
@font-face {
  font-family: "${CSS_FAMILY}";
  font-style: normal;
  font-weight: ${WEIGHT};
  font-display: ${DISPLAY};
  src: url("${SRC}") format("woff2");
${URANGE:+  unicode-range: ${URANGE};}
}
CSSBLOCK
done
