#!/bin/bash
# 美家卡智影 - 测试服一键部署脚本
# ================================
# 用法:
#   chmod +x deploy-test.sh
#   ./deploy-test.sh

set -e

echo "========================================"
echo "  美家卡智影 - 测试服部署"
echo "========================================"

# 配置
PROJECT_DIR="/opt/meijiaka-zy"
GIT_REPO="http://git2.haodian.cn/xiaoyu/meijiaka-zy.git"
API_PORT=8081
COMPOSE_FILE="docker-compose.test.yml"

# 1. 检查 Docker
echo "[1/7] 检查 Docker 环境..."
if ! command -v docker &> /dev/null; then
    echo "Docker 未安装，请先安装 Docker"
    exit 1
fi
if ! command -v docker-compose &> /dev/null && ! docker compose version &> /dev/null; then
    echo "Docker Compose 未安装，请先安装 Docker Compose"
    exit 1
fi

echo "Docker 版本: $(docker --version)"
docker compose version || echo "docker-compose 版本: $(docker-compose --version)"

# 2. 克隆/更新代码
echo "[2/7] 更新代码..."
if [ -d "$PROJECT_DIR/.git" ]; then
    cd "$PROJECT_DIR"
    git fetch origin master
    git reset --hard origin/master
else
    git clone "$GIT_REPO" "$PROJECT_DIR"
    cd "$PROJECT_DIR"
fi

# 3. 创建数据目录
echo "[3/7] 创建数据目录..."
mkdir -p /opt/meijiaka-zy/data/{postgres,redis,logs}
chmod 755 /opt/meijiaka-zy/data

# 4. 检查环境变量
echo "[4/7] 检查环境变量..."
cd "$PROJECT_DIR/python-api"

if [ ! -f ".env" ]; then
    echo "⚠️  .env 文件不存在，从 .env.example 复制..."
    if [ -f ".env.example" ]; then
        cp .env.example .env
        echo "⚠️  请编辑 .env 文件，填入实际的 API Key 后再重新运行此脚本"
        echo "   vim $PROJECT_DIR/python-api/.env"
        exit 1
    else
        echo "❌ .env.example 也不存在，请手动创建 .env 文件"
        exit 1
    fi
fi

# 检查关键环境变量
MISSING_VARS=()
for var in SECRET_KEY VOLCENGINE_API_KEY VIDU_API_KEY; do
    if ! grep -q "^$var=" .env || grep -q "^$var=\$" .env; then
        MISSING_VARS+=($var)
    fi
done

if [ ${#MISSING_VARS[@]} -gt 0 ]; then
    echo "⚠️  .env 中缺少以下关键环境变量:"
    for var in "${MISSING_VARS[@]}"; do
        echo "   - $var"
    done
    echo "   请编辑 .env 文件填入后再部署"
    exit 1
fi

echo "✅ 环境变量检查通过"

# 5. 构建镜像
echo "[5/7] 构建 Docker 镜像..."
docker compose -f "$COMPOSE_FILE" build --pull

# 6. 启动服务
echo "[6/7] 启动服务..."
docker compose -f "$COMPOSE_FILE" down 2>/dev/null || true
docker compose -f "$COMPOSE_FILE" up -d

# 7. 等待并验证
echo "[7/7] 等待服务启动..."
sleep 5

MAX_RETRY=12
RETRY=0
while [ $RETRY -lt $MAX_RETRY ]; do
    if curl -s http://localhost:$API_PORT/health | grep -q "healthy"; then
        # 验证 scheduler 容器也在运行
        if ! docker ps --filter "name=meijiaka-zy-scheduler" --filter "status=running" -q | grep -q .; then
            echo "⚠️  API 已就绪，但 scheduler 容器未运行，请检查日志"
        fi
        echo ""
        echo "========================================"
        echo "  ✅ 测试服部署成功！"
        echo "========================================"
        echo "  API 地址:    http://<服务器IP>:$API_PORT"
        echo "  健康检查:    http://<服务器IP>:$API_PORT/health"
        echo "  API 文档:    http://<服务器IP>:$API_PORT/docs"
        echo "  数据库:      localhost:5432 (meijiaka_zy)"
        echo "  Redis:       localhost:6379 (db 0)"
        echo ""
        echo "  查看日志:"
        echo "    docker logs -f meijiaka-zy-api"
        echo "    docker logs -f meijiaka-zy-scheduler"
        echo ""
        echo "  常用命令:"
        echo "    cd $PROJECT_DIR/python-api"
        echo "    docker compose -f $COMPOSE_FILE logs -f"
        echo "    docker compose -f $COMPOSE_FILE restart api"
        echo "========================================"
        exit 0
    fi
    RETRY=$((RETRY + 1))
    echo "  等待服务就绪... ($RETRY/$MAX_RETRY)"
    sleep 3
done

echo "❌ 服务启动超时，请检查日志:"
echo "   docker logs meijiaka-zy-api"
exit 1
