#!/bin/bash
# TSP智能助手部署脚本
# 支持多环境部署、版本管理、自动备份

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

# 颜色定义
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
NC='\033[0m' # No Color

# 日志函数
log_info() {
    echo -e "${GREEN}[INFO]${NC} $1"
}

log_warn() {
    echo -e "${YELLOW}[WARN]${NC} $1"
}

log_error() {
    echo -e "${RED}[ERROR]${NC} $1"
}

# 检查依赖
check_dependencies() {
    log_info "检查系统依赖..."
    
    # 检查Python
    if ! command -v python3 &> /dev/null; then
        log_error "Python3 未安装"
        exit 1
    fi
    
    # 检查pip
    if ! command -v pip3 &> /dev/null; then
        log_error "pip3 未安装"
        exit 1
    fi
    
    # 检查Git
    if ! command -v git &> /dev/null; then
        log_error "Git 未安装"
        exit 1
    fi
    
    log_info "依赖检查完成"
}

# 创建虚拟环境
setup_venv() {
    local venv_path=$1
    log_info "创建虚拟环境: $venv_path"
    
    if [ ! -d "$venv_path" ]; then
        python3 -m venv "$venv_path"
    fi
    
    source "$venv_path/bin/activate"
    pip install --upgrade pip
    log_info "虚拟环境设置完成"
}

# 安装依赖
install_dependencies() {
    log_info "安装Python依赖..."
    pip install -r requirements.txt
    log_info "依赖安装完成"
}

# 数据库迁移
run_migrations() {
    log_info "运行数据库迁移..."
    
    # 检查数据库文件
    if [ ! -f "tsp_assistant.db" ]; then
        log_info "初始化数据库..."
        python init_database.py
    fi
    
    log_info "数据库迁移完成"
}

# 创建systemd服务文件
create_systemd_service() {
    local service_name=$1
    local app_path=$2
    local service_file="/etc/systemd/system/${service_name}.service"
    
    log_info "创建systemd服务文件: $service_file"
    
    sudo tee "$service_file" > /dev/null <<EOF
[Unit]
Description=TSP智能助手服务
After=network.target

[Service]
Type=simple
User=www-data
Group=www-data
WorkingDirectory=$app_path
Environment=PATH=$app_path/venv/bin
ExecStart=$app_path/venv/bin/python start_dashboard.py
Restart=always
RestartSec=10

[Install]
WantedBy=multi-user.target
EOF

    sudo systemctl daemon-reload
    sudo systemctl enable "$service_name"
    log_info "systemd服务创建完成"
}

# 创建nginx配置
create_nginx_config() {
    local domain=$1
    local app_port=$2
    local config_file="/etc/nginx/sites-available/tsp_assistant"
    
    log_info "创建nginx配置: $config_file"
    
    sudo tee "$config_file" > /dev/null <<EOF
server {
    listen 80;
    server_name $domain;
    
    location / {
        proxy_pass http://127.0.0.1:$app_port;
        proxy_set_header Host \$host;
        proxy_set_header X-Real-IP \$remote_addr;
        proxy_set_header X-Forwarded-For \$proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto \$scheme;
    }
    
    location /static {
        alias $app_path/src/web/static;
        expires 1y;
        add_header Cache-Control "public, immutable";
    }
}
EOF

    # 启用站点
    sudo ln -sf "$config_file" /etc/nginx/sites-enabled/
    sudo nginx -t
    sudo systemctl reload nginx
    log_info "nginx配置完成"
}

# 主部署函数
deploy() {
    local environment=${1:-production}
    local domain=${2:-localhost}
    local app_port=${3:-5000}
    
    log_info "开始部署TSP智能助手到 $environment 环境"
    
    # 设置部署路径
    case $environment in
        development)
            DEPLOY_PATH="./dev_deploy"
            SERVICE_NAME=""
            ;;
        staging)
            DEPLOY_PATH="/opt/tsp_assistant_staging"
            SERVICE_NAME="tsp_assistant_staging"
            ;;
        production)
            DEPLOY_PATH="/opt/tsp_assistant"
            SERVICE_NAME="tsp_assistant"
            ;;
        *)
            log_error "未知环境: $environment"
            exit 1
            ;;
    esac
    
    # 检查依赖
    check_dependencies
    
    # 创建部署目录
    log_info "创建部署目录: $DEPLOY_PATH"
    sudo mkdir -p "$DEPLOY_PATH"
    sudo chown $USER:$USER "$DEPLOY_PATH"
    
    # 复制文件
    log_info "复制应用文件..."
    cp -r . "$DEPLOY_PATH/"
    cd "$DEPLOY_PATH"
    
    # 设置虚拟环境
    setup_venv "venv"
    
    # 安装依赖
    install_dependencies
    
    # 运行迁移
    run_migrations
    
    # 创建服务文件（非开发环境）
    if [ "$environment" != "development" ] && [ -n "$SERVICE_NAME" ]; then
        create_systemd_service "$SERVICE_NAME" "$DEPLOY_PATH"
        create_nginx_config "$domain" "$app_port"
    fi
    
    log_info "部署完成！"
    
    if [ "$environment" != "development" ]; then
        log_info "启动服务..."
        sudo systemctl start "$SERVICE_NAME"
        sudo systemctl status "$SERVICE_NAME"
    else
        log_info "开发环境部署完成，使用以下命令启动："
        log_info "cd $DEPLOY_PATH && source venv/bin/activate && python start_dashboard.py"
    fi
}

# 回滚函数
rollback() {
    local backup_name=$1
    
    if [ -z "$backup_name" ]; then
        log_error "请指定备份名称"
        exit 1
    fi
    
    log_info "回滚到备份: $backup_name"
    
    # 停止服务
    sudo systemctl stop tsp_assistant
    
    # 恢复备份
    if [ -d "backups/$backup_name" ]; then
        sudo rm -rf /opt/tsp_assistant
        sudo cp -r "backups/$backup_name" /opt/tsp_assistant
        sudo chown -R www-data:www-data /opt/tsp_assistant
        
        # 重启服务
        sudo systemctl start tsp_assistant
        log_info "回滚完成"
    else
        log_error "备份不存在: $backup_name"
        exit 1
    fi
}

# 版本检查
check_version() {
    log_info "检查版本信息..."
    if [ -f "version.json" ]; then
        local version=$(python3 -c "import json; print(json.load(open('version.json'))['version'])" 2>/dev/null || echo "unknown")
        log_info "当前版本: $version"
    else
        log_warn "版本文件不存在"
    fi
}

# 创建部署包
create_deployment_package() {
    local package_name="tsp_assistant_$(date +%Y%m%d_%H%M%S).tar.gz"
    log_info "创建部署包: $package_name"
    
    # 排除不需要的文件
    tar --exclude='.git' \
        --exclude='__pycache__' \
        --exclude='*.pyc' \
        --exclude='.env' \
        --exclude='logs/*' \
        --exclude='backups/*' \
        --exclude='dev_deploy' \
        -czf "$package_name" .
    
    log_info "部署包创建完成: $package_name"
    echo "$package_name"
}

# 主函数
main() {
    case ${1:-deploy} in
        deploy)
            check_version
            deploy "$2" "$3" "$4"
            ;;
        rollback)
            rollback "$2"
            ;;
        package)
            create_deployment_package
            ;;
        *)
            echo "用法: $0 {deploy|rollback|package} [environment] [domain] [port]"
            echo "环境: development, staging, production"
            echo ""
            echo "命令说明:"
            echo "  deploy    - 部署到指定环境"
            echo "  rollback  - 回滚到指定备份"
            echo "  package   - 创建部署包"
            exit 1
            ;;
    esac
}

main "$@"
