#!/bin/bash

# 算法展示平台完整启动脚本

echo "启动算法展示平台服务..."

# 进入部署目录
cd "$(dirname "$0")/deploy"

# 停止现有服务
echo "停止现有服务..."
docker-compose -f custom-docker-compose.yml down || true

# 启动基础服务
echo "启动基础服务 (PostgreSQL, Redis, MinIO)..."
HTTP_PROXY="" http_proxy="" HTTPS_PROXY="" https_proxy="" \
docker-compose -f custom-docker-compose.yml up -d postgres redis minio

echo "等待基础服务启动..."
sleep 15

# 检查基础服务状态
echo "检查基础服务状态..."
docker-compose -f custom-docker-compose.yml ps

echo ""
echo "基础服务已启动！"
echo ""

# 启动后端服务（假设镜像已构建）
echo "启动后端服务..."
HTTP_PROXY="" http_proxy="" HTTPS_PROXY="" https_proxy="" \
docker-compose -f custom-docker-compose.yml up -d backend

echo "等待后端服务启动..."
sleep 20

# 检查后端服务状态
BACKEND_STATUS=$(docker-compose -f custom-docker-compose.yml ps backend --format json | jq -r '.State' 2>/dev/null || echo 'unknown')

if [ "$BACKEND_STATUS" = "running" ]; then
    echo "后端服务已成功启动"
else
    echo "后端服务启动出现问题，状态: $BACKEND_STATUS"
    echo "尝试重新构建后端服务..."
    HTTP_PROXY="" http_proxy="" HTTPS_PROXY="" https_proxy="" \
    docker-compose -f custom-docker-compose.yml build backend
    HTTP_PROXY="" http_proxy="" HTTPS_PROXY="" https_proxy="" \
    docker-compose -f custom-docker-compose.yml up -d backend
fi

# 由于前端构建可能遇到网络问题，提供一个选项
echo ""
echo "是否尝试启动前端服务？(y/n)"
read -r frontend_choice

if [[ $frontend_choice =~ ^[Yy]$ ]]; then
    echo "尝试启动前端服务..."
    HTTP_PROXY="" http_proxy="" HTTPS_PROXY="" https_proxy="" \
    docker-compose -f custom-docker-compose.yml up -d frontend
    sleep 10
fi

echo ""
echo "等待所有服务启动..."
sleep 10

# 显示所有服务状态
echo "检查所有服务状态..."
docker-compose -f custom-docker-compose.yml ps

echo ""
echo "算法展示平台已启动！"
echo ""
echo "服务地址:"
echo "- 前端: http://localhost:3000"
echo "- 后端API: http://localhost:8000"
echo "- API文档: http://localhost:8000/docs"
echo "- MinIO控制台: http://localhost:9001 (admin/minioadmin)"
echo "- PostgreSQL: localhost:5433 (内部端口5432)"
echo "- Redis: localhost:6381 (内部端口6379)"
echo ""
echo "如需查看日志，请运行: docker-compose -f custom-docker-compose.yml logs -f"