#!/bin/bash
set -e

echo "============================================"
echo "  平台自动化测试系统 - Docker 部署脚本"
echo "============================================"
echo ""

# 检查 Docker
if ! command -v docker &> /dev/null; then
    echo "❌ 错误: Docker 未安装"
    echo "   请先安装 Docker: sudo apt-get install -y docker.io docker-compose-v2"
    echo "   或参考: https://docs.docker.com/engine/install/"
    exit 1
fi

# 检查 Docker Compose
if ! docker compose version &> /dev/null; then
    echo "❌ 错误: Docker Compose 未安装"
    exit 1
fi

# 获取脚本所在目录
SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
PROJECT_DIR="$(dirname "$SCRIPT_DIR")"

echo "📁 项目目录: $PROJECT_DIR"
echo ""

# 创建数据目录
echo "📂 创建数据目录..."
mkdir -p "$PROJECT_DIR/data/screenshots" "$PROJECT_DIR/data/reports"
echo "   ✅ 数据目录已就绪"

# 构建镜像
echo ""
echo "📦 构建 Docker 镜像..."
cd "$SCRIPT_DIR"
docker compose build
echo "   ✅ 镜像构建完成"

# 启动服务
echo ""
echo "🚀 启动服务..."
docker compose up -d
echo "   ✅ 服务已启动"

# 等待服务就绪
echo ""
echo "⏳ 等待服务就绪..."
sleep 10

# 健康检查
echo ""
echo "🔍 执行健康检查..."
MAX_RETRIES=6
RETRY_COUNT=0
while [ $RETRY_COUNT -lt $MAX_RETRIES ]; do
    HEALTH=$(curl -s -o /dev/null -w "%{http_code}" http://localhost:8001/health 2>/dev/null || echo "000")
    if [ "$HEALTH" = "200" ]; then
        echo "   ✅ 后端健康检查通过 (HTTP 200)"
        break
    fi
    RETRY_COUNT=$((RETRY_COUNT + 1))
    if [ $RETRY_COUNT -lt $MAX_RETRIES ]; then
        echo "   ⏳ 等待后端就绪... ($RETRY_COUNT/$MAX_RETRIES)"
        sleep 5
    fi
done

if [ $RETRY_COUNT -ge $MAX_RETRIES ]; then
    echo "   ⚠️  后端健康检查超时，请检查日志: docker compose logs backend"
fi

# 检查前端
FRONTEND_CODE=$(curl -s -o /dev/null -w "%{http_code}" http://localhost/ 2>/dev/null || echo "000")
if [ "$FRONTEND_CODE" = "200" ]; then
    echo "   ✅ 前端可访问 (HTTP 200)"
else
    echo "   ⚠️  前端响应码: $FRONTEND_CODE"
fi

# 检查已有服务是否受影响
TROUBLESHOOT_CODE=$(curl -s -o /dev/null -w "%{http_code}" http://localhost:8088/ 2>/dev/null || echo "000")
echo "   ℹ️  已有故障排查平台 (8088): HTTP $TROUBLESHOOT_CODE"

# 输出访问信息
echo ""
echo "============================================"
echo "  ✅ 部署完成！"
echo "============================================"
echo ""
echo "   前端:      http://$(curl -s ifconfig.me 2>/dev/null || hostname -I 2>/dev/null | awk '{print $1}' || echo 'localhost')"
echo "   API 文档:  http://localhost:8001/docs"
echo ""
echo "   已有故障排查平台: http://localhost:8088（不受影响）"
echo ""
echo "   📋 查看日志: docker compose logs -f"
echo "   🛑 停止服务: docker compose down"
echo "   🔄 重启服务: docker compose restart"
echo ""

# 检查容器状态
echo "📊 容器状态:"
docker compose ps