#!/bin/bash

# 智能算法展示平台部署脚本

set -e  # 遇到错误立即退出

echo "开始部署智能算法展示平台..."

# 检查必要的命令
command -v docker >/dev/null 2>&1 || { echo >&2 "Docker is required but not installed. Aborting."; exit 1; }
command -v docker-compose >/dev/null 2>&1 || { echo >&2 "Docker Compose is required but not installed. Aborting."; exit 1; }

# 检查Docker守护进程是否运行
if ! docker info >/dev/null 2>&1; then
    echo >&2 "Docker daemon is not running. Please start Docker and try again."
    exit 1
fi

# 检查环境变量文件
if [ ! -f ".env" ]; then
    echo "警告: .env 文件不存在，将使用默认配置"
    echo "请参考 .env.example 创建 .env 文件"
    echo "OPENAI_API_KEY=your_openai_api_key_here" > .env
    echo "SECRET_KEY=your_secret_key_here" >> .env
fi

# 加载环境变量
export $(grep -v '^#' .env | xargs)

# 检查Docker镜像是否存在，如果不存在则尝试拉取
IMAGES=("postgres:14-alpine" "redis:7-alpine" "minio/minio:latest" "nginx:alpine")

for image in "${IMAGES[@]}"; do
    if ! docker images --format "{{.Repository}}:{{.Tag}}" | grep -q "$(echo $image | sed 's/:.*//'):$(echo $image | sed 's/.*://')"; then
        echo "拉取镜像: $image"
        if ! docker pull "$image"; then
            echo "警告: 无法拉取镜像 $image，这可能导致后续构建失败"
            echo "您可以尝试配置Docker镜像加速器或检查网络连接"
        fi
    else
        echo "镜像已存在: $image"
    fi
done

# 构建并启动服务
echo "构建并启动服务..."
docker-compose -f docker-compose-full.yml up -d --build

# 等待服务启动
echo "等待服务启动..."
sleep 15

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

echo ""
echo "检查服务健康状态..."
SERVICES=("postgres" "redis" "minio" "backend" "frontend")

for service in "${SERVICES[@]}"; do
    sleep 3
    if [ "$(docker-compose -f docker-compose-full.yml ps $service --format json 2>/dev/null | jq -r '.State' 2>/dev/null || echo 'unknown')" = "running" ]; then
        echo "✓ $service 服务正在运行"
    else
        echo "✗ $service 服务未运行或存在问题"
    fi
done

echo ""
echo "部署完成!"
echo ""
echo "服务地址:"
echo "- 前端: http://localhost:3000"
echo "- 后端API: http://localhost:8000"
echo "- MinIO控制台: http://localhost:9001 (admin/minioadmin)"
echo ""
echo "要查看日志，请运行: docker-compose -f docker-compose-full.yml logs -f"

# 提供额外的故障排除信息
echo ""
echo "如遇问题，可尝试以下操作:"
echo "1. 检查Docker是否正常运行"
echo "2. 检查端口8000, 3000, 5432, 6379, 9000, 9001是否已被占用"
echo "3. 运行 'docker-compose -f docker-compose-full.yml logs' 查看详细日志"