#!/bin/bash
# Predador — launcher do bundle .app (duplo-clique)
HERE="$(cd "$(dirname "$0")" && pwd)"
RES="$(cd "$HERE/../Resources" && pwd)"
APPDIR="$RES/app"
DATA="$HOME/Library/Application Support/Predador"
VENV="$DATA/venv"
mkdir -p "$DATA"
LOG="$DATA/launch.log"
exec >>"$LOG" 2>&1
echo "=== launch $(date) ==="

notify(){ /usr/bin/osascript -e "display notification \"$1\" with title \"Predador\"" >/dev/null 2>&1 || true; }
errdlg(){ /usr/bin/osascript -e "display dialog \"$1\" with title \"Predador\" buttons {\"OK\"} default button 1 with icon stop" >/dev/null 2>&1 || true; }

# 1) Python 3
PY="$(command -v python3 || true)"
if [ -z "$PY" ]; then
  errdlg "O Predador precisa do Python 3. Vou abrir o instalador das Ferramentas de Linha de Comando da Apple. Depois de instalar, abra o Predador novamente."
  xcode-select --install >/dev/null 2>&1 || true
  exit 1
fi

# 2) Ambiente + dependencias (apenas na 1a vez)
if [ ! -x "$VENV/bin/python" ]; then
  notify "Preparando o Predador (primeira vez, pode levar alguns minutos)…"
  if ! "$PY" -m venv "$VENV"; then errdlg "Falha ao criar o ambiente Python. Veja o log em $LOG"; exit 1; fi
  "$VENV/bin/pip" install --upgrade pip
  if ! "$VENV/bin/pip" install -r "$RES/requirements.txt"; then
    "$VENV/bin/pip" install flask flask-cors playwright openpyxl || { errdlg "Falha ao instalar as bibliotecas. Veja $LOG"; exit 1; }
  fi
  "$VENV/bin/python" -m playwright install chromium || { errdlg "Falha ao baixar o navegador. Veja $LOG"; exit 1; }
  notify "Predador pronto!"
fi

# 3) Servidor + navegador
rm -f "$DATA/.porta"
( cd "$APPDIR" && nohup "$VENV/bin/python" server.py >>"$DATA/server.log" 2>&1 & )
for i in $(seq 1 40); do [ -f "$DATA/.porta" ] && break; sleep 1; done
PORTA="$(cat "$DATA/.porta" 2>/dev/null || echo 5000)"
if [ -z "$PORTA" ]; then errdlg "O servidor nao iniciou. Veja $DATA/server.log"; exit 1; fi
if [ -z "$PREDADOR_NO_OPEN" ]; then /usr/bin/open "http://localhost:$PORTA"; else echo "OPEN http://localhost:$PORTA"; fi
