#!/bin/bash
# 本地开发启动脚本

set -e

echo "=========================================="
echo "充电桩监控 - 本地开发环境"
echo "=========================================="

# 端口配置
BACKEND_PORT=${BACKEND_PORT:-5001}
FRONTEND_PORT=${FRONTEND_PORT:-8080}

# 停止已有进程
echo "[1/4] 清理旧进程..."
pkill -f "python3.*server.py" 2>/dev/null || true
pkill -f "python3.*http.server" 2>/dev/null || true
sleep 1

# 启动后端
echo "[2/4] 启动后端 API (端口 $BACKEND_PORT)..."
cd backend
FLASK_PORT=$BACKEND_PORT python3 server.py > /tmp/charger-backend.log 2>&1 &
BACKEND_PID=$!
cd ..
sleep 2

# 检查后端是否启动
if curl -s "http://localhost:$BACKEND_PORT/health" > /dev/null; then
    echo "      ✓ 后端启动成功 (PID: $BACKEND_PID)"
else
    echo "      ✗ 后端启动失败，查看日志: /tmp/charger-backend.log"
    exit 1
fi

# 启动前端静态服务器
echo "[3/4] 启动前端服务 (端口 $FRONTEND_PORT)..."
cd frontend
python3 -m http.server $FRONTEND_PORT > /tmp/charger-frontend.log 2>&1 &
FRONTEND_PID=$!
cd ..
sleep 1

if curl -s "http://localhost:$FRONTEND_PORT" > /dev/null; then
    echo "      ✓ 前端启动成功 (PID: $FRONTEND_PID)"
else
    echo "      ✗ 前端启动失败"
    exit 1
fi

# 输出访问信息
echo ""
echo "=========================================="
echo "🚀 服务已启动!"
echo "=========================================="
echo ""
echo "📱 前端页面:"
echo "   http://localhost:$FRONTEND_PORT"
echo ""
echo "🔌 后端 API:"
echo "   http://localhost:$BACKEND_PORT"
echo "   http://localhost:$BACKEND_PORT/api/station/\$STATION_ID"
echo ""
echo "📊 订阅列表:"
echo "   http://localhost:$BACKEND_PORT/api/subscriptions"
echo ""
echo "=========================================="
echo "按 Ctrl+C 停止所有服务"
echo "=========================================="

# 自动打开浏览器
if command -v open &> /dev/null; then
    open "http://localhost:$FRONTEND_PORT"
elif command -v xdg-open &> /dev/null; then
    xdg-open "http://localhost:$FRONTEND_PORT"
fi

# 等待用户中断
trap "echo ''; echo '停止服务...'; kill $BACKEND_PID $FRONTEND_PID 2>/dev/null; exit 0" INT TERM
wait
