#!/bin/bash

# 小红书投放系统生产环境部署脚本

set -e

# 颜色定义
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
PURPLE='\033[0;35m'
CYAN='\033[0;36m'
WHITE='\033[1;37m'
BOLD='\033[1m'
NC='\033[0m'

# 项目根目录
PROJECT_ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
cd "$PROJECT_ROOT"

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

log_success() {
    echo -e "${GREEN}[SUCCESS]${NC} $1"
}

log_warning() {
    echo -e "${YELLOW}[WARNING]${NC} $1"
}

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

log_header() {
    echo -e "${CYAN}$1${NC}"
}

# 检查依赖
check_dependencies() {
    log_header "🔍 检查部署依赖..."
    
    # 检查Docker
    if ! command -v docker &> /dev/null; then
        log_error "Docker 未安装，请先安装 Docker"
        exit 1
    fi
    
    # 检查Docker Compose
    if ! command -v docker-compose &> /dev/null; then
        log_error "Docker Compose 未安装，请先安装 Docker Compose"
        exit 1
    fi
    
    # 检查Docker是否运行
    if ! docker info &> /dev/null; then
        log_error "Docker 服务未运行，请启动 Docker"
        exit 1
    fi
    
    log_success "所有依赖检查通过"
}

# 环境变量检查
check_environment() {
    log_header "⚙️ 检查环境变量..."
    
    # 创建.env文件模板
    if [[ ! -f ".env" ]]; then
        log_info "创建环境变量文件..."
        cat > .env << EOF
# 生产环境配置
ENV=production

# 数据库配置
POSTGRES_DB=xiaohongshu
POSTGRES_USER=postgres
POSTGRES_PASSWORD=your_secure_password_here

# Redis配置
REDIS_PASSWORD=your_redis_password_here

# 告警配置
ALERT_WEBHOOK_URL=https://your-webhook-url.com/alerts
ALERT_EMAIL=admin@yourcompany.com
EMAIL_USERNAME=your-email@gmail.com
EMAIL_PASSWORD=your-email-password

# 备份配置
BACKUP_SCHEDULE=0 2 * * *
BACKUP_RETENTION_DAYS=30

# SSL配置（可选）
SSL_CERT_PATH=./docker/ssl/cert.pem
SSL_KEY_PATH=./docker/ssl/key.pem
EOF
        log_warning "请编辑 .env 文件，设置正确的环境变量"
        log_warning "特别注意修改数据库密码、邮件配置等敏感信息"
    fi
    
    # 检查必要的环境变量
    source .env
    
    if [[ "$POSTGRES_PASSWORD" == "your_secure_password_here" ]]; then
        log_error "请修改 .env 文件中的数据库密码"
        exit 1
    fi
    
    log_success "环境变量检查完成"
}

# 创建必要的目录
create_directories() {
    log_header "📁 创建必要的目录..."
    
    directories=(
        "data"
        "logs"
        "logs/nginx"
        "backups"
        "docker/ssl"
        "docker/grafana/dashboards"
        "docker/grafana/datasources"
        "docker/logstash/pipeline"
    )
    
    for dir in "${directories[@]}"; do
        if [[ ! -d "$dir" ]]; then
            mkdir -p "$dir"
            log_info "创建目录: $dir"
        fi
    done
    
    log_success "目录创建完成"
}

# 构建Docker镜像
build_images() {
    log_header "🔨 构建Docker镜像..."
    
    # 构建主应用镜像
    log_info "构建小红书投放系统镜像..."
    docker build -f docker/Dockerfile.xiaohongshu -t xiaohongshu-main:latest .
    
    # 构建声音克隆MCP镜像
    if [[ -d "mcp-services/voice-clone/voice-clone-mcp" ]]; then
        log_info "构建声音克隆MCP镜像..."
        cd mcp-services/voice-clone/voice-clone-mcp
        docker build -t voice-clone-mcp:latest .
        cd "$PROJECT_ROOT"
    fi
    
    # 构建健康检查镜像
    log_info "构建健康检查镜像..."
    docker build -f docker/healthcheck/Dockerfile -t xiaohongshu-healthcheck:latest docker/healthcheck/
    
    # 构建备份镜像
    log_info "构建备份镜像..."
    docker build -f docker/backup/Dockerfile -t xiaohongshu-backup:latest docker/backup/
    
    log_success "Docker镜像构建完成"
}

# 初始化数据库
init_database() {
    log_header "🗄️ 初始化数据库..."
    
    # 启动数据库服务
    docker-compose -f docker-compose.production.yml up -d postgres
    
    # 等待数据库启动
    log_info "等待数据库启动..."
    sleep 30
    
    # 检查数据库连接
    for i in {1..30}; do
        if docker-compose -f docker-compose.production.yml exec -T postgres pg_isready -U postgres; then
            log_success "数据库连接成功"
            break
        fi
        
        if [[ $i -eq 30 ]]; then
            log_error "数据库启动超时"
            exit 1
        fi
        
        sleep 2
    done
    
    log_success "数据库初始化完成"
}

# 部署服务
deploy_services() {
    log_header "🚀 部署生产环境服务..."
    
    # 停止现有服务
    log_info "停止现有服务..."
    docker-compose -f docker-compose.production.yml down
    
    # 启动所有服务
    log_info "启动生产环境服务..."
    docker-compose -f docker-compose.production.yml up -d
    
    # 等待服务启动
    log_info "等待服务启动..."
    sleep 60
    
    log_success "服务部署完成"
}

# 健康检查
health_check() {
    log_header "🏥 执行健康检查..."
    
    services=(
        "xiaohongshu-main:8080"
        "xiaohongshu-nginx:80"
        "xiaohongshu-redis:6379"
        "xiaohongshu-postgres:5432"
        "xiaohongshu-prometheus:9090"
        "xiaohongshu-grafana:3000"
    )
    
    healthy_count=0
    total_count=${#services[@]}
    
    for service in "${services[@]}"; do
        service_name=$(echo "$service" | cut -d':' -f1)
        port=$(echo "$service" | cut -d':' -f2)
        
        log_info "检查服务: $service_name"
        
        if docker ps | grep -q "$service_name"; then
            if [[ "$service_name" == "xiaohongshu-nginx" ]]; then
                if curl -s "http://localhost:$port/health" > /dev/null; then
                    log_success "✅ $service_name - 健康"
                    ((healthy_count++))
                else
                    log_warning "❌ $service_name - 不健康"
                fi
            else
                log_success "✅ $service_name - 运行中"
                ((healthy_count++))
            fi
        else
            log_warning "❌ $service_name - 未运行"
        fi
    done
    
    echo ""
    log_info "健康检查完成: $healthy_count/$total_count 服务正常"
    
    if [[ $healthy_count -eq $total_count ]]; then
        log_success "🎉 所有服务运行正常！"
        return 0
    else
        log_warning "⚠️ 部分服务异常，请检查日志"
        return 1
    fi
}

# 显示部署信息
show_deployment_info() {
    log_header "📋 部署信息"
    echo "=================================================="
    echo ""
    echo "🔗 服务访问地址:"
    echo "   • 主应用: http://localhost"
    echo "   • API文档: http://localhost/docs"
    echo "   • Grafana监控: http://localhost:3000 (admin/admin123)"
    echo "   • Prometheus: http://localhost:9090"
    echo "   • Kibana日志: http://localhost:5601"
    echo ""
    echo "🔧 管理命令:"
    echo "   • 查看服务状态: docker-compose -f docker-compose.production.yml ps"
    echo "   • 查看日志: docker-compose -f docker-compose.production.yml logs -f [service]"
    echo "   • 重启服务: docker-compose -f docker-compose.production.yml restart [service]"
    echo "   • 停止所有服务: docker-compose -f docker-compose.production.yml down"
    echo ""
    echo "📊 监控和日志:"
    echo "   • 应用日志: ./logs/"
    echo "   • Nginx日志: ./logs/nginx/"
    echo "   • 备份文件: ./backups/"
    echo ""
    echo "🔐 安全提醒:"
    echo "   • 请修改默认密码"
    echo "   • 配置SSL证书（生产环境）"
    echo "   • 设置防火墙规则"
    echo "   • 定期更新系统和依赖"
    echo ""
}

# 主函数
main() {
    log_header "🚀 小红书投放系统生产环境部署"
    echo "=================================================="
    echo ""
    
    # 检查参数
    case "${1:-deploy}" in
        "check")
            check_dependencies
            check_environment
            ;;
        "build")
            check_dependencies
            build_images
            ;;
        "deploy")
            check_dependencies
            check_environment
            create_directories
            build_images
            init_database
            deploy_services
            
            # 等待服务完全启动
            sleep 30
            
            if health_check; then
                show_deployment_info
                log_success "🎉 生产环境部署成功！"
            else
                log_error "❌ 部署过程中发现问题，请检查服务状态"
                exit 1
            fi
            ;;
        "health")
            health_check
            ;;
        "stop")
            log_info "停止所有服务..."
            docker-compose -f docker-compose.production.yml down
            log_success "所有服务已停止"
            ;;
        "restart")
            log_info "重启所有服务..."
            docker-compose -f docker-compose.production.yml restart
            log_success "所有服务已重启"
            ;;
        "logs")
            docker-compose -f docker-compose.production.yml logs -f "${2:-}"
            ;;
        "help"|"-h"|"--help")
            echo "用法: $0 <command>"
            echo ""
            echo "命令:"
            echo "  deploy    完整部署（默认）"
            echo "  check     检查部署环境"
            echo "  build     构建Docker镜像"
            echo "  health    健康检查"
            echo "  stop      停止所有服务"
            echo "  restart   重启所有服务"
            echo "  logs      查看日志"
            echo "  help      显示帮助信息"
            ;;
        *)
            log_error "未知命令: $1"
            echo "使用 '$0 help' 查看帮助信息"
            exit 1
            ;;
    esac
}

# 运行主函数
main "$@"
