#!/bin/bash
# Karaokezera para macOS — inicializador.
# Garante yt-dlp + ffmpeg + python (via Homebrew), sobe o servidor local e abre a tela da TV.

set -u
RES_DIR="$(cd "$(dirname "$0")/../Resources" && pwd)"
PORT="${KZ_PORT:-5555}"
LOG_DIR="$HOME/Library/Logs"
LOG="$LOG_DIR/Karaokezera.log"
STAMP="$HOME/Library/Application Support/Karaokezera/last-update"
export PATH="/opt/homebrew/bin:/opt/homebrew/sbin:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin:${PATH:-}"
export KZ_PORT="$PORT"
mkdir -p "$LOG_DIR" "$(dirname "$STAMP")"

notify() { osascript -e "display notification \"$1\" with title \"Karaokezera\"" >/dev/null 2>&1 || true; }
alert()  { osascript -e "display dialog \"$1\" with title \"Karaokezera\" buttons {\"OK\"} default button 1 with icon caution" >/dev/null 2>&1 || true; }

echo "===== $(date) — iniciando Karaokezera =====" >>"$LOG"

# Já está rodando? Só abre a TV de novo.
if curl -fsS "http://127.0.0.1:$PORT/api/state" >/dev/null 2>&1; then
  open "http://localhost:$PORT/tv"
  exit 0
fi

# 1) Homebrew
if ! command -v brew >/dev/null 2>&1; then
  choice=$(osascript -e 'button returned of (display dialog "O Karaokezera precisa do Homebrew para instalar o yt-dlp e o ffmpeg.\n\nAbra o site, copie o comando de instalação, cole no app Terminal e depois abra o Karaokezera de novo." with title "Karaokezera" buttons {"Cancelar", "Abrir brew.sh"} default button 2 with icon caution)' 2>/dev/null)
  [ "$choice" = "Abrir brew.sh" ] && open "https://brew.sh/pt-br/"
  exit 1
fi
BREW_PREFIX="$(brew --prefix)"

find_python() {
  for c in "$BREW_PREFIX/bin/python3" "/opt/homebrew/bin/python3" "/usr/local/bin/python3"; do
    [ -x "$c" ] && { echo "$c"; return 0; }
  done
  return 1
}

# 2) Dependências (só instala na primeira vez)
missing=()
command -v yt-dlp >/dev/null 2>&1 || missing+=("yt-dlp")
command -v ffmpeg >/dev/null 2>&1 || missing+=("ffmpeg")
find_python >/dev/null || missing+=("python")

if [ ${#missing[@]} -gt 0 ]; then
  notify "Instalando ${missing[*]}… (só na primeira vez, pode levar alguns minutos)"
  if ! brew install "${missing[@]}" >>"$LOG" 2>&1; then
    alert "Não consegui instalar: ${missing[*]}.\n\nTente no Terminal:\nbrew install yt-dlp ffmpeg python\n\nDetalhes no log: $LOG"
    exit 1
  fi
  date +%s >"$STAMP"
else
  # O YouTube muda com frequência e o yt-dlp precisa estar atualizado: confere 1x por dia.
  last=$(cat "$STAMP" 2>/dev/null || echo 0)
  if [ $(( $(date +%s) - last )) -gt 86400 ]; then
    ( brew upgrade yt-dlp >>"$LOG" 2>&1; date +%s >"$STAMP" ) &
  fi
fi

PY="$(find_python)" || { alert "Python 3 não encontrado. Rode no Terminal: brew install python"; exit 1; }

# 3) Servidor
"$PY" "$RES_DIR/server.py" >>"$LOG" 2>&1 &
SERVER_PID=$!
trap 'kill "$SERVER_PID" 2>/dev/null' TERM INT HUP

for _ in $(seq 1 40); do
  curl -fsS "http://127.0.0.1:$PORT/api/state" >/dev/null 2>&1 && break
  if ! kill -0 "$SERVER_PID" 2>/dev/null; then
    alert "O servidor do Karaokezera não conseguiu iniciar (a porta $PORT pode estar em uso).\n\nDetalhes no log: $LOG"
    exit 1
  fi
  sleep 0.25
done

open "http://localhost:$PORT/tv"
notify "Rodando! Coloque a janela do navegador na TV e peça músicas pelo QR code."

wait "$SERVER_PID"
