#!/usr/bin/env bash
# Deploy independente do backend FastAPI/pipeline.
set -euo pipefail

APP_DIR="${DEPLOY_PATH:-}"
if [[ -z "$APP_DIR" ]]; then
  SCRIPT_DIR="$(CDPATH= cd -- "$(dirname -- "$0")" && pwd)"
  APP_DIR="$(dirname -- "$SCRIPT_DIR")"
fi
APP_DIR="${APP_DIR%/}"

VENV_DIR="$APP_DIR/.venv"
ENV_FILE="$APP_DIR/.env"
PID_FILE="$APP_DIR/logs/api.pid"
LOG_FILE="$APP_DIR/logs/api.log"

if [[ ! -f "$APP_DIR/requirements.txt" ]] || [[ ! -d "$APP_DIR/src/keepedu_performance" ]]; then
  echo "[ERRO] Backend nao encontrado em $APP_DIR." >&2
  exit 1
fi

mkdir -p "$APP_DIR/logs"

load_root_env() {
  [[ -f "$ENV_FILE" ]] || {
    echo "[ERRO] Arquivo de ambiente ausente: $ENV_FILE" >&2
    exit 1
  }
  set -a
  while IFS= read -r line || [[ -n "$line" ]]; do
    line="${line%$'\r'}"
    [[ -z "${line//[[:space:]]/}" || "$line" =~ ^[[:space:]]*# ]] && continue
    if [[ "$line" =~ ^[[:space:]]*([A-Za-z_][A-Za-z0-9_]*)=(.*)$ ]]; then
      key="${BASH_REMATCH[1]}"
      value="${BASH_REMATCH[2]}"
      if [[ "$value" =~ ^\"(.*)\"$ ]]; then value="${BASH_REMATCH[1]}"; fi
      if [[ "$value" =~ ^\'(.*)\'$ ]]; then value="${BASH_REMATCH[1]}"; fi
      export "$key=$value"
    fi
  done < "$ENV_FILE"
  set +a
}

load_root_env
API_HOST_VALUE="${API_HOST:-127.0.0.1}"
API_PORT_VALUE="${PORT:-${API_PORT:-8000}}"

PY=""
for candidate in "${PYTHON_BIN:-}" python3.10 python3.11 python3.12 python3; do
  [[ -n "$candidate" ]] || continue
  if command -v "$candidate" >/dev/null 2>&1; then
    PY="$candidate"
    break
  fi
done
[[ -n "$PY" ]] || { echo "[ERRO] Python 3 nao encontrado." >&2; exit 1; }

if [[ ! -x "$VENV_DIR/bin/python" ]]; then
  "$PY" -m venv "$VENV_DIR"
fi
"$VENV_DIR/bin/pip" install --upgrade pip
"$VENV_DIR/bin/pip" install -r "$APP_DIR/requirements.txt"

stop_pid() {
  local pid="${1:-}"
  [[ -n "$pid" ]] || return 0
  if kill -0 "$pid" 2>/dev/null; then
    kill "$pid" 2>/dev/null || true
    for _ in 1 2 3 4 5; do
      kill -0 "$pid" 2>/dev/null || return 0
      sleep 1
    done
    kill -9 "$pid" 2>/dev/null || true
  fi
}

if [[ -f "$PID_FILE" ]]; then
  stop_pid "$(cat "$PID_FILE" 2>/dev/null || true)"
  rm -f "$PID_FILE"
fi

# Recupera listeners legados quando o arquivo de PID estiver ausente ou obsoleto.
LISTENER_PIDS=""
if command -v fuser >/dev/null 2>&1; then
  fuser -k "${API_PORT_VALUE}/tcp" 2>/dev/null || true
elif command -v lsof >/dev/null 2>&1; then
  LISTENER_PIDS="$(lsof -t -iTCP:"$API_PORT_VALUE" -sTCP:LISTEN 2>/dev/null || true)"
elif command -v ss >/dev/null 2>&1; then
  LISTENER_PIDS="$(ss -ltnp "sport = :$API_PORT_VALUE" 2>/dev/null | sed -nE 's/.*pid=([0-9]+).*/\1/p' | sort -u)"
fi
for listener_pid in $LISTENER_PIDS; do
  stop_pid "$listener_pid"
done

cd "$APP_DIR"
echo "==> Iniciando API em $API_HOST_VALUE:$API_PORT_VALUE"
PYTHONPATH="$APP_DIR/src" nohup "$VENV_DIR/bin/python" -m uvicorn \
  keepedu_performance.api.app:app --host "$API_HOST_VALUE" --port "$API_PORT_VALUE" \
  >"$LOG_FILE" 2>&1 &
echo $! > "$PID_FILE"

for _ in 1 2 3 4 5 6 7 8 9 10; do
  if "$VENV_DIR/bin/python" -c \
    "import urllib.request; urllib.request.urlopen('http://${API_HOST_VALUE}:${API_PORT_VALUE}/health/live', timeout=2)" \
    >/dev/null 2>&1; then
    echo "==> Deploy concluido: pid=$(cat "$PID_FILE")"
    exit 0
  fi
  sleep 1
done

echo "[ERRO] API nao respondeu ao health check." >&2
tail -n 80 "$LOG_FILE" >&2 || true
exit 1
