#!/bin/bash

# QAUP 主部署脚本
# 用于在客户环境中一键部署 QAUP 系统

set -e

SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
PROJECT_ROOT="$(cd "$SCRIPT_DIR/.." && pwd)"

# 颜色输出
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m'

print_message() {
    local color=$1
    local message=$2
    echo -e "${color}${message}${NC}"
}

print_banner() {
    echo ""
    print_message $BLUE "========================================="
    print_message $BLUE "    QAUP 系统 Docker 部署脚本"
    print_message $BLUE "========================================="
    echo ""
}

# 检查系统要求
check_prerequisites() {
    print_message $BLUE "检查系统要求..."
    
    local errors=0
    
    # 检查 Docker
    if ! command -v docker &> /dev/null; then
        print_message $RED "✗ Docker 未安装"
        errors=$((errors + 1))
    else
        print_message $GREEN "✓ Docker 已安装"
    fi
    
    # 检查 Docker Compose
    if ! command -v docker-compose &> /dev/null; then
        print_message $RED "✗ Docker Compose 未安装"
        errors=$((errors + 1))
    else
        print_message $GREEN "✓ Docker Compose 已安装"
    fi
    
    # 检查 curl
    if ! command -v curl &> /dev/null; then
        print_message $YELLOW "⚠ curl 未安装，建议安装以支持健康检查"
    else
        print_message $GREEN "✓ curl 已安装"
    fi
    
    if [ $errors -gt 0 ]; then
        print_message $RED "系统要求检查失败，请安装缺失的组件"
        exit 1
    fi
    
    print_message $GREEN "系统要求检查通过"
}

# 初始化配置
initialize_config() {
    print_message $BLUE "初始化配置..."
    
    # 运行配置管理器
    if [ -x "$PROJECT_ROOT/docker/config-manager.sh" ]; then
        "$PROJECT_ROOT/docker/config-manager.sh" init
    else
        print_message $RED "配置管理脚本不存在或不可执行"
        exit 1
    fi
    
    print_message $GREEN "配置初始化完成"
}

# 验证环境
validate_environment() {
    print_message $BLUE "验证部署环境..."
    
    if [ -x "$PROJECT_ROOT/docker/validate-environment.sh" ]; then
        if "$PROJECT_ROOT/docker/validate-environment.sh"; then
            print_message $GREEN "环境验证通过"
        else
            print_message $RED "环境验证失败，请修复问题后重试"
            exit 1
        fi
    else
        print_message $YELLOW "环境验证脚本不存在，跳过验证"
    fi
}

# 构建镜像
build_images() {
    print_message $BLUE "构建 Docker 镜像..."
    
    cd "$PROJECT_ROOT"
    
    # 使用 Docker Compose 管理器构建
    if [ -x "$PROJECT_ROOT/docker/docker-compose-manager.sh" ]; then
        "$PROJECT_ROOT/docker/docker-compose-manager.sh" prod build
    else
        # 直接使用 docker-compose 构建
        docker-compose -f docker-compose.yml -f docker-compose.prod.yml build
    fi
    
    print_message $GREEN "镜像构建完成"
}

# 启动服务
start_services() {
    print_message $BLUE "启动服务..."
    
    cd "$PROJECT_ROOT"
    
    # 使用 Docker Compose 管理器启动
    if [ -x "$PROJECT_ROOT/docker/docker-compose-manager.sh" ]; then
        "$PROJECT_ROOT/docker/docker-compose-manager.sh" prod start
    else
        # 直接使用 docker-compose 启动
        docker-compose -f docker-compose.yml -f docker-compose.prod.yml up -d
    fi
    
    print_message $GREEN "服务启动完成"
}

# 等待服务就绪
wait_for_services() {
    print_message $BLUE "等待服务就绪..."
    
    local max_wait=300  # 最大等待5分钟
    local wait_time=0
    local interval=10
    
    while [ $wait_time -lt $max_wait ]; do
        if curl -f -s http://localhost/health &>/dev/null; then
            print_message $GREEN "✓ 服务已就绪"
            return 0
        fi
        
        print_message $YELLOW "等待服务启动... (${wait_time}s/${max_wait}s)"
        sleep $interval
        wait_time=$((wait_time + interval))
    done
    
    print_message $RED "服务启动超时"
    return 1
}

# 运行健康检查
run_health_checks() {
    print_message $BLUE "运行健康检查..."
    
    if [ -x "$PROJECT_ROOT/docker/monitor.sh" ]; then
        "$PROJECT_ROOT/docker/monitor.sh" health
    else
        print_message $YELLOW "监控脚本不存在，跳过健康检查"
    fi
}

# 显示部署信息
show_deployment_info() {
    print_message $GREEN "========================================="
    print_message $GREEN "    QAUP 系统部署完成！"
    print_message $GREEN "========================================="
    echo ""
    
    print_message $BLUE "访问信息:"
    echo "  前端地址: http://localhost"
    echo "  API 地址: http://localhost/prod-api"
    echo "  健康检查: http://localhost/health"
    echo ""
    
    print_message $BLUE "管理命令:"
    echo "  查看状态: docker/docker-compose-manager.sh prod status"
    echo "  查看日志: docker/log-manager.sh view all"
    echo "  系统监控: docker/monitor.sh watch"
    echo "  停止服务: docker/docker-compose-manager.sh prod stop"
    echo ""
    
    print_message $BLUE "重要文件:"
    echo "  环境配置: .env"
    echo "  日志目录: ./logs/"
    echo "  数据目录: ./data/"
    echo "  备份目录: ./backup/"
    echo ""
    
    print_message $YELLOW "注意事项:"
    echo "  1. 请妥善保管 .env 文件中的密码"
    echo "  2. 定期备份数据库和配置文件"
    echo "  3. 监控系统资源使用情况"
    echo "  4. 查看部署文档了解更多管理命令"
}

# 清理部署
cleanup_deployment() {
    print_message $YELLOW "清理部署..."
    
    read -p "确定要清理部署吗？这将删除所有容器和数据 (y/N): " -n 1 -r
    echo
    if [[ $REPLY =~ ^[Yy]$ ]]; then
        cd "$PROJECT_ROOT"
        
        if [ -x "$PROJECT_ROOT/docker/docker-compose-manager.sh" ]; then
            "$PROJECT_ROOT/docker/docker-compose-manager.sh" prod clean
        else
            docker-compose -f docker-compose.yml -f docker-compose.prod.yml down -v
            docker system prune -f
        fi
        
        print_message $GREEN "部署清理完成"
    else
        print_message $BLUE "取消清理操作"
    fi
}

# 更新部署
update_deployment() {
    print_message $BLUE "更新部署..."
    
    # 备份当前配置
    if [ -x "$PROJECT_ROOT/docker/config-manager.sh" ]; then
        "$PROJECT_ROOT/docker/config-manager.sh" backup
    fi
    
    # 重新构建镜像
    build_images
    
    # 重启服务
    cd "$PROJECT_ROOT"
    if [ -x "$PROJECT_ROOT/docker/docker-compose-manager.sh" ]; then
        "$PROJECT_ROOT/docker/docker-compose-manager.sh" prod restart
    else
        docker-compose -f docker-compose.yml -f docker-compose.prod.yml restart
    fi
    
    # 等待服务就绪
    wait_for_services
    
    print_message $GREEN "部署更新完成"
}

# 显示帮助信息
show_help() {
    echo "QAUP Docker 部署脚本"
    echo ""
    echo "用法: $0 [命令] [选项]"
    echo ""
    echo "命令:"
    echo "  install     完整安装部署"
    echo "  start       启动服务"
    echo "  stop        停止服务"
    echo "  restart     重启服务"
    echo "  status      查看状态"
    echo "  update      更新部署"
    echo "  cleanup     清理部署"
    echo "  logs        查看日志"
    echo "  monitor     系统监控"
    echo ""
    echo "示例:"
    echo "  $0 install             # 完整安装"
    echo "  $0 start               # 启动服务"
    echo "  $0 logs app            # 查看应用日志"
    echo "  $0 monitor             # 系统监控"
}

# 完整安装流程
full_install() {
    print_banner
    
    print_message $BLUE "开始 QAUP 系统完整安装..."
    echo ""
    
    # 执行安装步骤
    check_prerequisites
    echo ""
    
    initialize_config
    echo ""
    
    validate_environment
    echo ""
    
    build_images
    echo ""
    
    start_services
    echo ""
    
    if wait_for_services; then
        echo ""
        run_health_checks
        echo ""
        show_deployment_info
    else
        print_message $RED "部署失败，请检查日志"
        exit 1
    fi
}

# 主函数
main() {
    if [ $# -eq 0 ]; then
        show_help
        exit 0
    fi
    
    local command=$1
    shift
    
    case $command in
        install)
            full_install
            ;;
        start)
            start_services
            wait_for_services
            ;;
        stop)
            if [ -x "$PROJECT_ROOT/docker/docker-compose-manager.sh" ]; then
                "$PROJECT_ROOT/docker/docker-compose-manager.sh" prod stop
            else
                docker-compose -f docker-compose.yml -f docker-compose.prod.yml stop
            fi
            ;;
        restart)
            if [ -x "$PROJECT_ROOT/docker/docker-compose-manager.sh" ]; then
                "$PROJECT_ROOT/docker/docker-compose-manager.sh" prod restart
            else
                docker-compose -f docker-compose.yml -f docker-compose.prod.yml restart
            fi
            wait_for_services
            ;;
        status)
            if [ -x "$PROJECT_ROOT/docker/docker-compose-manager.sh" ]; then
                "$PROJECT_ROOT/docker/docker-compose-manager.sh" prod status
            else
                docker-compose -f docker-compose.yml -f docker-compose.prod.yml ps
            fi
            ;;
        update)
            update_deployment
            ;;
        cleanup)
            cleanup_deployment
            ;;
        logs)
            if [ -x "$PROJECT_ROOT/docker/log-manager.sh" ]; then
                "$PROJECT_ROOT/docker/log-manager.sh" view "$@"
            else
                docker-compose -f docker-compose.yml -f docker-compose.prod.yml logs -f "$@"
            fi
            ;;
        monitor)
            if [ -x "$PROJECT_ROOT/docker/monitor.sh" ]; then
                "$PROJECT_ROOT/docker/monitor.sh" watch
            else
                print_message $YELLOW "监控脚本不存在"
            fi
            ;;
        help|--help|-h)
            show_help
            ;;
        *)
            print_message $RED "未知命令: $command"
            show_help
            exit 1
            ;;
    esac
}

main "$@"