#!/bin/bash
set -e

echo "============================================"
echo "  平台自动化测试系统 - V2 Docker 部署脚本"
echo "  架构: 合一应用容器 + MySQL"
echo "============================================"
echo ""

# 检查 Docker
if ! command -v docker &> /dev/null; then
    echo "❌ 错误: Docker 未安装"
    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="/data/third_party/plat-auto-test"

echo "📁 部署目录: $PROJECT_DIR"
echo ""

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

# 检查 .env 文件
if [ ! -f "$SCRIPT_DIR/.env" ]; then
    echo "⚠️  .env 文件不存在，从 .env.example 复制..."
    cp "$SCRIPT_DIR/.env.example" "$SCRIPT_DIR/.env"
    echo "   ⚠️  请检查 .env 中的数据库密码配置"
fi

# 检查后端代码是否存在
if [ ! -d "$PROJECT_DIR/backend/app" ]; then
    echo "⚠️  后端代码不存在，请先上传后端代码到 $PROJECT_DIR/backend/"
    exit 1
fi

# 检查前端构建产物是否存在
if [ ! -f "$PROJECT_DIR/frontend/dist/index.html" ]; then
    echo "⚠️  前端构建产物不存在，请先上传 dist/ 到 $PROJECT_DIR/frontend/dist/"
    echo "   本地构建: cd frontend && npm run build"
    echo "   上传: scp -r dist/* ubains@192.168.5.60:$PROJECT_DIR/frontend/dist/"
    exit 1
fi

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

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

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

# 健康检查
echo ""
echo "🔍 执行健康检查..."
MAX_RETRIES=12
RETRY_COUNT=0
while [ $RETRY_COUNT -lt $MAX_RETRIES ]; do
    HEALTH=$(curl -s -o /dev/null -w "%{http_code}" http://localhost/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 app"
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

# 检查 MySQL
MYSQL_OK=$(docker exec plat-auto-test-mysql mysqladmin ping -h localhost -uroot -p"${MYSQL_ROOT_PASSWORD:-Ubains@13579}" 2>/dev/null || echo "failed")
if [ "$MYSQL_OK" != "failed" ]; then
    echo "   ✅ MySQL 运行正常"
else
    echo "   ⚠️  MySQL 状态异常，请检查: docker compose logs mysql"
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://192.168.5.60"
echo "   API 文档:  http://192.168.5.60/docs"
echo ""
echo "   已有维护平台: http://192.168.5.60:8088（不受影响）"
echo ""
echo "   📋 查看日志: docker compose logs -f"
echo "   🛑 停止服务: docker compose down"
echo "   🔄 重启应用: docker compose restart app"
echo ""

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