#!/bin/bash
set -euo pipefail

# Sino-MCI 本地开发启动脚本
# 自动加载项目根目录 .env 文件中的环境变量，然后启动后端或前端。
#
# 用法：
#   ./scripts/run-local.sh backend
#   ./scripts/run-local.sh frontend
#   ./scripts/run-local.sh channel
#
# 切换环境：
#   cp .env.local .env   # 本地基础设施
#   cp .env.remote .env  # 远程基础设施（如 192.168.1.173）

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
PROJECT_ROOT="$SCRIPT_DIR/.."
cd "$PROJECT_ROOT"

if [ ! -f .env ]; then
  echo ".env file not found. Creating from .env.local ..."
  cp .env.local .env
fi

# 加载 .env（忽略注释与空行）
set -o allexport
# shellcheck source=/dev/null
source .env
set +o allexport

echo "Loaded environment from: $PROJECT_ROOT/.env"
echo "  MYSQL_HOST=${MYSQL_HOST:-localhost}"
echo "  REDIS_HOST=${REDIS_HOST:-localhost}"
echo "  RABBITMQ_HOST=${RABBITMQ_HOST:-localhost}"
echo "  MCI_SERVER_URL=${MCI_SERVER_URL:-http://localhost:8080/msg-platform}"
echo "  VITE_API_BASE_URL=${VITE_API_BASE_URL:-http://localhost:8080}"
echo ""

SERVICE=${1:-}
if [ -z "$SERVICE" ]; then
  echo "Usage: $0 <backend|frontend|channel>"
  exit 1
fi

case "$SERVICE" in
  backend|server)
    cd backend/mci-server
    echo "Starting mci-server with Maven..."
    ./mvnw spring-boot:run -Dspring-boot.run.profiles=dev
    ;;
  frontend|web)
    cd admin-web
    echo "Starting admin-web with Vite..."
    npm run dev
    ;;
  channel|channel-service)
    cd channel-service
    echo "Starting channel-service..."
    if [ ! -d .venv ]; then
      python3 -m venv .venv
    fi
    source .venv/bin/activate
    pip install -r requirements.txt -q
    python -m app.main
    ;;
  *)
    echo "Unknown service: $SERVICE"
    echo "Usage: $0 <backend|frontend|channel>"
    exit 1
    ;;
esac
