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

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
REPO_ROOT="$(cd "$SCRIPT_DIR/.." && pwd)"
LOG_DIR="$REPO_ROOT/logs"
PID_FILE="$LOG_DIR/web_dashboard.pid"
LOG_FILE="$LOG_DIR/web_dashboard.log"

mkdir -p "$LOG_DIR"

if [[ -f "$REPO_ROOT/.env.dashboard" ]]; then
  # shellcheck disable=SC1091
  source "$REPO_ROOT/.env.dashboard"
fi

export API_FOOTBALL_BASE_URL="${API_FOOTBALL_BASE_URL:-https://v3.football.api-sports.io}"

if [[ -z "${API_FOOTBALL_KEY:-}" ]]; then
  echo "[ERROR] 缺少 API_FOOTBALL_KEY 环境变量。"
  echo "可选做法："
  echo "  1) export API_FOOTBALL_KEY=你的key"
  echo "  2) 在 $REPO_ROOT/.env.dashboard 中写入：API_FOOTBALL_KEY=你的key"
  exit 1
fi

if [[ -f "$PID_FILE" ]]; then
  OLD_PID="$(cat "$PID_FILE" 2>/dev/null || true)"
  if [[ -n "$OLD_PID" ]] && kill -0 "$OLD_PID" 2>/dev/null; then
    echo "[INFO] dashboard 已在运行，PID=$OLD_PID"
    echo "[INFO] 地址: http://127.0.0.1:8765"
    exit 0
  fi
fi

if command -v fuser >/dev/null 2>&1; then
  fuser -k 8765/tcp 2>/dev/null || true
fi

cd "$REPO_ROOT"
nohup python3 -u scripts/web_dashboard.py > "$LOG_FILE" 2>&1 &
NEW_PID=$!
echo "$NEW_PID" > "$PID_FILE"

sleep 3
if kill -0 "$NEW_PID" 2>/dev/null; then
  echo "[OK] dashboard 已启动"
  echo "[OK] PID=$NEW_PID"
  echo "[OK] 地址: http://127.0.0.1:8765"
  echo "[OK] 日志: $LOG_FILE"
else
  echo "[ERROR] dashboard 启动失败，请查看日志: $LOG_FILE"
  exit 1
fi
