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

FONT_ZIP_URL="https://github.com/ryanoasis/nerd-fonts/releases/latest/download/JetBrainsMono.zip"

is_macos() { [[ "$(uname -s)" == "Darwin" ]]; }

echo "🔎 Installerer JetBrainsMono Nerd Font (best effort)"

if is_macos; then
  # Try Homebrew first (best UX on mac)
  if command -v brew >/dev/null 2>&1; then
    echo "🍺 Homebrew funnet – prøver cask..."
    brew tap homebrew/cask-fonts >/dev/null 2>&1 || true
    if brew install --cask font-jetbrains-mono-nerd-font; then
      echo "✅ Installert via Homebrew cask."
      echo "Velg fonten i terminal: JetBrainsMono Nerd Font"
      exit 0
    fi
    echo "⚠️ Cask feilet, faller tilbake til manuell install."
  fi

  FONT_DIR="$HOME/Library/Fonts"
  mkdir -p "$FONT_DIR"
  tmpzip="$(mktemp -t jbmono.XXXXXX.zip)"
  curl -fsSL "$FONT_ZIP_URL" -o "$tmpzip"
  tmpdir="$(mktemp -d -t jbmono.XXXXXX)"
  unzip -o "$tmpzip" -d "$tmpdir" >/dev/null
  rm -f "$tmpzip"

  # Copy only TTF/OTF
  find "$tmpdir" -type f \( -iname "*.ttf" -o -iname "*.otf" \) -maxdepth 2 -print0 \
    | xargs -0 -I{} cp -f "{}" "$FONT_DIR"/
  rm -rf "$tmpdir"

  echo "✅ Font kopiert til $FONT_DIR"
  echo "Velg fonten i terminal: JetBrainsMono Nerd Font"
  exit 0
fi

# Linux
FONT_DIR="$HOME/.local/share/fonts"
mkdir -p "$FONT_DIR"
tmpzip="$(mktemp --suffix=.zip)"
curl -fsSL "$FONT_ZIP_URL" -o "$tmpzip"
unzip -o "$tmpzip" -d "$FONT_DIR" >/dev/null
rm -f "$tmpzip"
fc-cache -f >/dev/null 2>&1 || true
echo "✅ Font installert i $FONT_DIR"
echo "Velg fonten i terminal: JetBrainsMono Nerd Font"
