#!/usr/bin/env bash
# Pós-deploy no servidor (GitHub Actions ou SSH manual).
#
# Variáveis opcionais:
#   DEPLOY_PATH     — pasta do projeto (padrão: diretório atual)
#   SERVICE_NAME    — unit systemd (padrão: omrcheck-web)
#   PYTHON_BIN      — interpretador (padrão: python3.11 … python3)
#   SKIP_MIGRATE    — se "1", não roda init_database.py
#   SKIP_RESTART    — se "1", não reinicia o systemd
#   ALLOW_RESTART_FAILURE — se "1", não falha o deploy se o restart falhar
set -euo pipefail

APP_DIR="${DEPLOY_PATH:-${APP_DIR:-$(pwd)}}"
APP_DIR="${APP_DIR%/}"
SERVICE_NAME="${SERVICE_NAME:-omrcheck-web}"
VENV_DIR="${APP_DIR}/.venv"
HEALTH_URL="${HEALTH_URL:-http://127.0.0.1:8000/healthz}"

if [ -z "${APP_DIR}" ]; then
  echo "[ERRO] DEPLOY_PATH não definido."
  exit 1
fi

if [ ! -d "${APP_DIR}" ]; then
  echo "[ERRO] Pasta de deploy não existe: ${APP_DIR}"
  echo "Crie no servidor: mkdir -p ${APP_DIR}"
  exit 1
fi

cd "${APP_DIR}"

if [ ! -f "requirements-prod.txt" ]; then
  echo "[ERRO] Arquivos do projeto não encontrados em ${APP_DIR}."
  echo "Verifique o secret DEPLOY_PATH (deve ser a mesma pasta usada no rsync)."
  exit 1
fi

PY=""
for c in "${PYTHON_BIN:-}" python3.13 python3.12 python3.11 python3.10 python3; do
  [ -n "$c" ] || continue
  if command -v "$c" >/dev/null 2>&1; then
    PY="$c"
    break
  fi
done

if [ -z "$PY" ]; then
  echo "[ERRO] Nenhum interpretador Python 3 encontrado no servidor."
  exit 1
fi

echo "==> Interpretador: $PY ($("$PY" --version 2>&1))"

if ! "$PY" -c 'import sys; sys.exit(0 if sys.version_info[:2] >= (3, 11) else 1)'; then
  echo "[ERRO] O projeto exige Python >= 3.11."
  exit 1
fi

echo "==> Virtualenv..."
if [ -d "$VENV_DIR" ] && [ ! -x "$VENV_DIR/bin/python" ]; then
  rm -rf "$VENV_DIR"
fi

if [ ! -d "$VENV_DIR" ]; then
  "$PY" -m venv "$VENV_DIR"
fi

# shellcheck source=/dev/null
source "${VENV_DIR}/bin/activate"

pip install --upgrade pip
pip install -r requirements-prod.txt

if [ ! -f ".env" ]; then
  echo "[ERRO] Arquivo .env não encontrado em:"
  echo "  ${APP_DIR}/.env"
  echo ""
  echo "O deploy não envia o .env (fica só no servidor)."
  echo "Crie/edite pelo cPanel File Manager na MESMA pasta do DEPLOY_PATH:"
  echo "  ${APP_DIR}"
  exit 1
fi

if [[ "${SKIP_MIGRATE:-0}" != "1" ]]; then
  echo "==> Banco + migrations / schema..."
  python scripts/init_database.py --criar-banco

  if ! python -c "from app.settings import APP_STORAGE_BACKEND; import sys; sys.exit(0 if APP_STORAGE_BACKEND == 'mysql' else 1)"; then
    echo "[ERRO] APP_STORAGE_BACKEND não é 'mysql' no .env do servidor."
    echo "Defina APP_STORAGE_BACKEND=mysql e as variáveis MYSQL_* / KEEPEDU_LOGIN_SCHOOL."
    exit 1
  fi
fi

_reiniciar_systemd() {
  local servico="$1"

  if [[ "$(id -u)" -eq 0 ]]; then
    systemctl restart "${servico}"
    systemctl is-active --quiet "${servico}"
    return 0
  fi

  if systemctl restart "${servico}" 2>/dev/null; then
    systemctl is-active --quiet "${servico}"
    return 0
  fi

  if sudo -n systemctl restart "${servico}" 2>/dev/null; then
    sudo -n systemctl is-active --quiet "${servico}"
    return 0
  fi

  echo "[ERRO] Não foi possível reiniciar ${servico}."
  echo "O usuário $(whoami) precisa de uma destas opções:"
  echo "  1) SSH_USER=root no GitHub Actions"
  echo "  2) sudo sem senha para systemctl (visudo)"
  echo "  3) Reiniciar manualmente: sudo systemctl restart ${servico}"
  return 1
}

if [[ "${SKIP_RESTART:-0}" != "1" ]]; then
  echo "==> Reiniciando ${SERVICE_NAME}..."
  if command -v systemctl &>/dev/null; then
    if ! _reiniciar_systemd "${SERVICE_NAME}"; then
      if [[ "${ALLOW_RESTART_FAILURE:-0}" == "1" ]]; then
        echo "[WARN] Deploy concluído, mas o serviço não foi reiniciado."
        echo "Use SSH_USER=root no GitHub ou: sudo systemctl restart ${SERVICE_NAME}"
      else
        exit 1
      fi
    fi
  else
    echo "[WARN] systemctl não disponível — reinicie a aplicação manualmente."
  fi
fi

if command -v curl &>/dev/null; then
  echo "==> Healthcheck ${HEALTH_URL}..."
  sleep 2
  curl -fsS "${HEALTH_URL}" || true
  echo ""
fi

echo "[OK] Deploy concluído."
