#!/bin/bash

# ========================================
# 邀请返佣系统完整部署脚本
# ========================================

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

# 配置变量
GO_PROJECT_PATH="/www/wwwroot/nofx"
HTML_PROJECT_PATH="/www/wwwroot/149.88.81.229_9000"
PM2_APP_NAME="nofx"
GIT_REPO="https://gitee.com/dreams619/quant-nova.git"

echo "=========================================="
echo "🚀 开始部署邀请返佣系统"
echo "=========================================="
echo ""

# ========================================
# 1. 后端部署
# ========================================
echo "📦 [1/4] 部署后端..."
echo "------------------------------------------"

# 检查 Go 项目目录是否存在
if [ ! -d "$GO_PROJECT_PATH" ]; then
    echo "❌ Go 项目目录不存在: $GO_PROJECT_PATH"
    exit 1
fi

cd "$GO_PROJECT_PATH"
echo "✓ 进入目录: $(pwd)"

# 拉取最新代码
echo "📥 拉取最新代码..."
git pull origin main
if [ $? -ne 0 ]; then
    echo "⚠️  Git 拉取失败，尝试重置..."
    git fetch origin
    git reset --hard origin/main
fi
echo "✓ 代码更新完成"

# 下载依赖
echo "📦 下载 Go 依赖..."
go mod tidy
echo "✓ 依赖下载完成"

# 编译
echo "🔨 编译后端程序..."
CGO_ENABLED=0 GOOS=linux GOARCH=amd64 go build -o nofx-linux main.go
if [ $? -ne 0 ]; then
    echo "❌ 编译失败！"
    exit 1
fi
echo "✓ 编译完成: nofx-linux"

# 备份旧版本
if [ -f "nofx-linux.old" ]; then
    rm -f nofx-linux.old
fi
if [ -f "nofx-linux" ]; then
    cp nofx-linux nofx-linux.old
    echo "✓ 已备份旧版本"
fi

echo ""

# ========================================
# 2. 前端部署
# ========================================
echo "🎨 [2/4] 部署前端..."
echo "------------------------------------------"

# 检查 web 目录
if [ ! -d "$GO_PROJECT_PATH/web" ]; then
    echo "❌ web 目录不存在"
    exit 1
fi

cd "$GO_PROJECT_PATH/web"
echo "✓ 进入目录: $(pwd)"

# 安装依赖
echo "📦 安装前端依赖..."
npm install --production
echo "✓ 依赖安装完成"

# 编译前端
echo "🔨 编译前端..."
npm run build
if [ $? -ne 0 ]; then
    echo "❌ 前端编译失败！"
    exit 1
fi
echo "✓ 前端编译完成"

# 备份旧的前端文件
echo "💾 备份旧的前端文件..."
if [ -d "$HTML_PROJECT_PATH/backup" ]; then
    rm -rf "$HTML_PROJECT_PATH/backup"
fi
mkdir -p "$HTML_PROJECT_PATH/backup"
cp -r "$HTML_PROJECT_PATH"/*.{html,js,css} "$HTML_PROJECT_PATH/backup/" 2>/dev/null || true
cp -r "$HTML_PROJECT_PATH/assets" "$HTML_PROJECT_PATH/backup/" 2>/dev/null || true
echo "✓ 备份完成"

# 部署前端文件
echo "📤 部署前端文件到 HTML 目录..."
cp -r dist/* "$HTML_PROJECT_PATH/"
if [ $? -ne 0 ]; then
    echo "❌ 前端文件复制失败！"
    exit 1
fi
echo "✓ 前端文件部署完成"

# 设置权限
chmod -R 755 "$HTML_PROJECT_PATH"
echo "✓ 权限设置完成"

echo ""

# ========================================
# 3. 数据库迁移
# ========================================
echo "🗄️  [3/4] 数据库迁移..."
echo "------------------------------------------"
echo "ℹ️  数据库迁移将在程序启动时自动执行"
echo "   - 添加邀请码字段"
echo "   - 创建返佣记录表"
echo "   - 创建邀请关系表"
echo "   - 添加会员返佣比例字段"
echo "✓ 无需手动操作"

echo ""

# ========================================
# 4. 重启服务
# ========================================
echo "🔄 [4/4] 重启服务..."
echo "------------------------------------------"

cd "$GO_PROJECT_PATH"

# 检查 PM2 是否安装
if ! command -v pm2 &> /dev/null; then
    echo "❌ PM2 未安装，请先安装 PM2"
    echo "   npm install -g pm2"
    exit 1
fi

# 停止旧进程
echo "⏸️  停止旧进程..."
pm2 stop "$PM2_APP_NAME" 2>/dev/null || echo "   (进程未运行)"

# 启动新进程
echo "▶️  启动新进程..."
pm2 start nofx-linux --name "$PM2_APP_NAME"
if [ $? -ne 0 ]; then
    echo "❌ 启动失败！尝试回滚..."
    if [ -f "nofx-linux.old" ]; then
        cp nofx-linux.old nofx-linux
        pm2 start nofx-linux --name "$PM2_APP_NAME"
        echo "⚠️  已回滚到旧版本"
    fi
    exit 1
fi

# 保存 PM2 配置
pm2 save

echo "✓ 服务启动成功"

echo ""

# ========================================
# 5. 验证部署
# ========================================
echo "✅ [验证] 检查部署状态..."
echo "------------------------------------------"

# 等待服务启动
sleep 3

# 检查进程状态
echo "📊 进程状态:"
pm2 list | grep "$PM2_APP_NAME"

# 检查 API 健康状态
echo ""
echo "🏥 API 健康检查:"
HEALTH_CHECK=$(curl -s http://localhost:8080/api/health || echo "failed")
if [[ "$HEALTH_CHECK" == *"ok"* ]] || [[ "$HEALTH_CHECK" == *"healthy"* ]]; then
    echo "✓ API 服务正常"
else
    echo "⚠️  API 服务可能未就绪，请查看日志"
fi

# 检查前端文件
echo ""
echo "📁 前端文件检查:"
if [ -f "$HTML_PROJECT_PATH/index.html" ]; then
    echo "✓ index.html 存在"
else
    echo "❌ index.html 不存在"
fi

if [ -d "$HTML_PROJECT_PATH/assets" ]; then
    echo "✓ assets 目录存在"
else
    echo "⚠️  assets 目录不存在"
fi

# 显示最近日志
echo ""
echo "📋 最近日志 (最后 20 行):"
echo "------------------------------------------"
pm2 logs "$PM2_APP_NAME" --lines 20 --nostream

echo ""
echo "=========================================="
echo "✅ 部署完成！"
echo "=========================================="
echo ""
echo "📌 访问地址:"
echo "   前端: http://149.88.81.229:9000"
echo "   后端: http://149.88.81.229:8080"
echo ""
echo "📌 常用命令:"
echo "   查看日志: pm2 logs $PM2_APP_NAME"
echo "   重启服务: pm2 restart $PM2_APP_NAME"
echo "   停止服务: pm2 stop $PM2_APP_NAME"
echo "   查看状态: pm2 status"
echo ""
echo "📌 回滚命令 (如果出现问题):"
echo "   cd $GO_PROJECT_PATH"
echo "   cp nofx-linux.old nofx-linux"
echo "   pm2 restart $PM2_APP_NAME"
echo "   cp -r $HTML_PROJECT_PATH/backup/* $HTML_PROJECT_PATH/"
echo ""
