#!/bin/bash
set -e

echo "============================================"
echo "  平台自动化测试系统 - 部署到 192.168.5.41"
echo "  架构: 合一应用容器(8081) + MySQL(3307)"
echo "============================================"
echo ""

# 检查 Docker
if ! command -v docker &> /dev/null; then
    echo "ERROR: Docker 未安装"
    exit 1
fi

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

# 获取脚本所在目录
SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
PROJECT_DIR="/data/third_party/plat-auto-test"

echo "deploy dir: $SCRIPT_DIR"
echo "target dir: $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 "   OK"

# 检查 .env 文件
ENV_FILE="$SCRIPT_DIR/.env"
if [ ! -f "$ENV_FILE" ]; then
    echo "WARNING: .env 不存在，从 .env.example 复制..."
    cp "$SCRIPT_DIR/.env.example" "$ENV_FILE"
fi

# 检查后端代码
if [ ! -d "$PROJECT_DIR/backend/app" ]; then
    echo "ERROR: 后端代码不存在 $PROJECT_DIR/backend/"
    exit 1
fi

# 检查前端构建产物
if [ ! -f "$PROJECT_DIR/frontend/dist/index.html" ]; then
    echo "ERROR: 前端构建产物不存在 $PROJECT_DIR/frontend/dist/"
    exit 1
fi

# 设置端口变量（供 docker-compose 使用）
export APP_PORT=8081
export MYSQL_PORT=3307

# 检查端口是否可用
if ss -tlnp | grep -q ":$APP_PORT "; then
    echo "WARNING: 端口 $APP_PORT 已被占用，请检查"
fi
if ss -tlnp | grep -q ":$MYSQL_PORT "; then
    echo "WARNING: 端口 $MYSQL_PORT 已被占用，请检查"
fi

# 构建镜像
echo ""
echo ">>> 构建 Docker 镜像..."
cd "$SCRIPT_DIR"
docker compose -f docker-compose.41.yml build
echo "   OK"

# 先启动 MySQL（等 MySQL 就绪后再启动 app，避免内存峰值）
echo ""
echo ">>> 启动 MySQL 容器..."
docker compose -f docker-compose.41.yml up -d mysql
echo "   OK"

# 等待 MySQL 就绪
echo ""
echo ">>> 等待 MySQL 就绪..."
MAX_RETRIES=30
RETRY_COUNT=0
while [ $RETRY_COUNT -lt $MAX_RETRIES ]; do
    if docker exec plat-auto-test-mysql mysqladmin ping -h localhost -uroot -p"${MYSQL_ROOT_PASSWORD:-Ubains@13579}" --silent 2>/dev/null; then
        echo "   MySQL 就绪"
        break
    fi
    RETRY_COUNT=$((RETRY_COUNT + 1))
    echo "   等待 MySQL... ($RETRY_COUNT/$MAX_RETRIES)"
    sleep 3
done

if [ $RETRY_COUNT -ge $MAX_RETRIES ]; then
    echo "WARNING: MySQL 就绪超时，继续尝试启动 app"
fi

# 启动应用容器
echo ""
echo ">>> 启动应用容器..."
docker compose -f docker-compose.41.yml up -d app
echo "   OK"

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

if [ $RETRY_COUNT -ge $MAX_RETRIES ]; then
    echo "WARNING: 应用健康检查超时，请检查日志: docker compose logs app"
fi

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

# 输出访问信息
echo ""
echo "============================================"
echo "  部署完成！"
echo "============================================"
echo ""
echo "   前端:      http://192.168.5.41:$APP_PORT"
echo "   API 文档:  http://192.168.5.41:$APP_PORT/docs"
echo "   健康检查:  http://192.168.5.41:$APP_PORT/health"
echo "   MySQL 端口:  $MYSQL_PORT"
echo ""
echo "   查看日志: docker compose -f docker-compose.41.yml logs -f"
echo "   停止服务: docker compose -f docker-compose.41.yml down"
echo "   重启应用: docker compose -f docker-compose.41.yml restart app"
echo ""

# 检查容器状态
echo ">>> 容器状态:"
docker compose -f docker-compose.41.yml ps