#!/bin/bash
# 甲辰藏品管理系统 v1.0.0 - 部署脚本
# 使用方式：./deploy.sh [版本号] [环境]
# 示例：./deploy.sh 1.0.0 production

set -e

VERSION=${1:-1.0.0}
ENV=${2:-test}

log_info() { echo "[INFO] $1"; }
log_error() { echo "[ERROR] $1" && exit 1; }

log_info "=== 甲辰藏品管理系统 v${VERSION} 部署开始 ==="
log_info "目标环境：$ENV"

# 获取脚本所在目录
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
PROJECT_ROOT="$(dirname "$SCRIPT_DIR")"

cd "$PROJECT_ROOT"

# 1. 备份当前版本
log_info "[1/6] 备份当前版本..."
BACKUP_DIR="$PROJECT_ROOT/backups/v$VERSION-$(date +%Y%m%d_%H%M%S)"
mkdir -p "$BACKUP_DIR"
cp -r backend "$BACKUP_DIR/" 2>/dev/null || true
cp -r frontend "$BACKUP_DIR/" 2>/dev/null || true
cp -r static "$BACKUP_DIR/" 2>/dev/null || true
log_info "备份完成：$BACKUP_DIR"

# 2. Git 提交（如果有 Git 仓库）
log_info "[2/6] Git 提交..."
if [ -d ".git" ]; then
    git add -A
    git commit -m "release(v$VERSION): 部署新版本" 2>/dev/null || log_info "无更改需要提交"
    git tag "v$VERSION" 2>/dev/null || true
    log_info "Git 操作完成"
else
    log_info "非 Git 仓库，跳过"
fi

# 3. 构建前端
log_info "[3/6] 构建前端..."
cd "$PROJECT_ROOT/frontend"
rm -rf dist
npm install
npm run build
log_info "前端构建完成"

# 检查 Logo 文件
log_info "[3.5/6] 检查 Logo 资源..."
if [ ! -f "$PROJECT_ROOT/static/images/jiachenlong-logo.png" ]; then
    log_error "Logo 文件不存在：static/images/jiachenlong-logo.png"
fi
log_info "Logo 文件确认：jiachenlong-logo.png"

# 4. 安装后端依赖
log_info "[4/6] 安装后端依赖..."
cd "$PROJECT_ROOT/backend"
pip3 install -r requirements.txt
log_info "后端依赖安装完成"

# 5. 部署（根据环境选择）
log_info "[5/6] 部署到服务器..."

if [ "$ENV" == "local" ]; then
    # 本地部署
    DEPLOY_DIR="/var/www/jiachenlong"
    mkdir -p "$DEPLOY_DIR/frontend"
    cp -r "$PROJECT_ROOT/frontend/dist/"* "$DEPLOY_DIR/frontend/"
    log_info "本地部署完成：$DEPLOY_DIR"
    
elif [ "$ENV" == "test" ]; then
    # 测试服务器
    SERVER="root@120.26.133.10"
    DEST_DIR="/var/www/mobile"
    
    # 部署前端构建文件
    cd "$PROJECT_ROOT/frontend/dist"
    tar -czf - . | ssh -o StrictHostKeyChecking=no "$SERVER" "cd $DEST_DIR && rm -rf dist/* && tar -xzf -"
    
    # 部署静态资源（包含 Logo）
    ssh -o StrictHostKeyChecking=no "$SERVER" "mkdir -p $DEST_DIR/static/images"
    scp -o StrictHostKeyChecking=no "$PROJECT_ROOT/static/images/jiachenlong-logo.png" "$SERVER:$DEST_DIR/static/images/"
    
    ssh -o StrictHostKeyChecking=no "$SERVER" "nginx -s reload"
    log_info "测试环境部署完成：http://120.26.133.10/"
    
elif [ "$ENV" == "production" ]; then
    # 生产服务器 A (WebA: 8.154.46.3)
    SERVER="root@8.154.46.3"
    DEPLOY_DIR="/var/www/frontend"
    
    # 部署前端构建文件
    cd "$PROJECT_ROOT/frontend/dist"
    tar -czf - . | ssh -o StrictHostKeyChecking=no "$SERVER" "cd $DEPLOY_DIR && rm -rf * && tar -xzf -"
    
    # 部署静态资源（包含 Logo）
    ssh -o StrictHostKeyChecking=no "$SERVER" "mkdir -p $DEPLOY_DIR/static/images"
    scp -o StrictHostKeyChecking=no "$PROJECT_ROOT/static/images/jiachenlong-logo.png" "$SERVER:$DEPLOY_DIR/static/images/"
    
    ssh -o StrictHostKeyChecking=no "$SERVER" "nginx -s reload"
    log_info "生产环境A部署完成：http://8.154.46.3/"
    scp -o StrictHostKeyChecking=no "$PROJECT_ROOT/static/images/jiachenlong-logo.png" "$SERVER:$DEST_DIR/static/images/"
    
    ssh -o StrictHostKeyChecking=no "$SERVER" "nginx -s reload"
    log_info "生产环境部署完成：http://$SERVER/"
    
else
    log_error "未知环境：$ENV (支持：local, test, production)"
fi

# 6. 重启后端服务
log_info "[6/6] 重启后端服务..."
pkill -f "uvicorn app.main:app" || true
sleep 2
cd "$PROJECT_ROOT/backend"
nohup python3 -m uvicorn app.main:app --port 3000 --host 0.0.0.0 > /tmp/uvicorn.log 2>&1 &
sleep 2

if curl -s http://localhost:3000/health | grep -q "healthy"; then
    log_info "后端服务启动成功"
else
    log_error "后端服务启动失败，请检查日志：/tmp/uvicorn.log"
fi

log_info "=== 部署完成 ==="
log_info "版本：v$VERSION"
log_info "环境：$ENV"
