#!/bin/bash

# 环境配置设置脚本
# 用于初始化和配置Docker部署环境

set -e

echo "==================================="
echo "Docker环境配置设置"
echo "==================================="

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

# 默认值
DEFAULT_ENV="production"
DEFAULT_DB_PASSWORD="secure_password_$(date +%s)"
DEFAULT_MEILISEARCH_KEY="master_key_$(openssl rand -hex 16)"

# 显示帮助信息
show_help() {
    echo "用法: $0 [选项]"
    echo ""
    echo "选项:"
    echo "  -e, --env ENV          设置环境类型 (production|development) [默认: production]"
    echo "  -i, --interactive      交互式配置"
    echo "  -f, --force           强制覆盖现有配置文件"
    echo "  -h, --help            显示此帮助信息"
    echo ""
    echo "示例:"
    echo "  $0 -e production       设置生产环境"
    echo "  $0 -e development      设置开发环境"
    echo "  $0 -i                  交互式配置"
}

# 解析命令行参数
ENV_TYPE="$DEFAULT_ENV"
INTERACTIVE=false
FORCE=false

while [[ $# -gt 0 ]]; do
    case $1 in
        -e|--env)
            ENV_TYPE="$2"
            shift 2
            ;;
        -i|--interactive)
            INTERACTIVE=true
            shift
            ;;
        -f|--force)
            FORCE=true
            shift
            ;;
        -h|--help)
            show_help
            exit 0
            ;;
        *)
            echo "未知选项: $1"
            show_help
            exit 1
            ;;
    esac
done

# 验证环境类型
if [[ "$ENV_TYPE" != "production" && "$ENV_TYPE" != "development" ]]; then
    echo -e "${RED}错误: 环境类型必须是 'production' 或 'development'${NC}"
    exit 1
fi

echo -e "${BLUE}配置环境类型: $ENV_TYPE${NC}"

# 交互式配置
if [ "$INTERACTIVE" = true ]; then
    echo ""
    echo "交互式配置模式"
    echo "-----------------------------------"
    
    read -p "应用名称 [知识库系统]: " app_name
    app_name=${app_name:-"知识库系统"}
    
    read -p "应用URL [http://localhost]: " app_url
    app_url=${app_url:-"http://localhost"}
    
    read -p "数据库名称 [knowledge_base]: " db_name
    db_name=${db_name:-"knowledge_base"}
    
    read -p "数据库用户名 [knowledge_user]: " db_user
    db_user=${db_user:-"knowledge_user"}
    
    read -s -p "数据库密码: " db_password
    echo ""
    
    read -s -p "Meilisearch主密钥: " meilisearch_key
    echo ""
    
    if [ "$ENV_TYPE" = "production" ]; then
        read -p "SMTP主机: " mail_host
        read -p "SMTP端口 [587]: " mail_port
        mail_port=${mail_port:-587}
        read -p "SMTP用户名: " mail_username
        read -s -p "SMTP密码: " mail_password
        echo ""
    fi
else
    # 非交互式配置，使用默认值
    app_name="知识库系统"
    app_url="http://localhost"
    db_name="knowledge_base"
    db_user="knowledge_user"
    db_password="$DEFAULT_DB_PASSWORD"
    meilisearch_key="$DEFAULT_MEILISEARCH_KEY"
fi

# 生成APP_KEY
echo ""
echo "生成应用密钥..."
echo "-----------------------------------"

if command -v php >/dev/null 2>&1; then
    # 如果有PHP，使用Laravel生成密钥
    if [ -f "artisan" ]; then
        app_key=$(php artisan key:generate --show)
        echo -e "${GREEN}✓ 使用Laravel生成APP_KEY${NC}"
    else
        # 生成base64编码的随机密钥
        app_key="base64:$(openssl rand -base64 32)"
        echo -e "${GREEN}✓ 使用OpenSSL生成APP_KEY${NC}"
    fi
else
    # 生成base64编码的随机密钥
    app_key="base64:$(openssl rand -base64 32)"
    echo -e "${GREEN}✓ 使用OpenSSL生成APP_KEY${NC}"
fi

# 确定环境文件名
if [ "$ENV_TYPE" = "production" ]; then
    env_file=".env.production"
    compose_file="docker-compose.yml"
else
    env_file=".env.development"
    compose_file="docker-compose.dev.yml"
    app_name="${app_name}-开发"
    db_name="${db_name}_dev"
    db_user="dev_user"
    app_url="http://localhost:8000"
fi

# 检查文件是否存在
if [ -f "$env_file" ] && [ "$FORCE" = false ]; then
    echo -e "${YELLOW}警告: $env_file 已存在${NC}"
    read -p "是否覆盖? (y/N): " overwrite
    if [[ ! "$overwrite" =~ ^[Yy]$ ]]; then
        echo "取消操作"
        exit 0
    fi
fi

# 创建环境文件
echo ""
echo "创建环境配置文件..."
echo "-----------------------------------"

cat > "$env_file" << EOF
# $ENV_TYPE 环境配置
# 由 setup-env.sh 自动生成于 $(date)

APP_NAME="$app_name"
APP_ENV=$ENV_TYPE
APP_KEY=$app_key
APP_DEBUG=$([ "$ENV_TYPE" = "development" ] && echo "true" || echo "false")
APP_URL=$app_url

APP_LOCALE=zh_CN
APP_FALLBACK_LOCALE=zh_CN
APP_FAKER_LOCALE=zh_CN

BCRYPT_ROUNDS=$([ "$ENV_TYPE" = "development" ] && echo "10" || echo "12")

LOG_CHANNEL=stack
LOG_STACK=single
LOG_LEVEL=$([ "$ENV_TYPE" = "development" ] && echo "debug" || echo "info")

# 数据库配置 - 使用Docker容器名称进行服务间通信
DB_CONNECTION=mysql
DB_HOST=mysql
DB_PORT=3306
DB_DATABASE=$db_name
DB_USERNAME=$db_user
DB_PASSWORD=$db_password

# 会话和缓存配置
SESSION_DRIVER=redis
SESSION_LIFETIME=120
SESSION_ENCRYPT=false

CACHE_STORE=redis
CACHE_PREFIX=$([ "$ENV_TYPE" = "development" ] && echo "kb_dev_cache" || echo "kb_cache")

# Redis配置 - 使用Docker容器名称进行服务间通信
REDIS_CLIENT=phpredis
REDIS_HOST=redis
REDIS_PORT=6379
REDIS_PASSWORD=

# 队列配置 - 使用Redis作为队列驱动
QUEUE_CONNECTION=redis

# 文件系统配置
FILESYSTEM_DISK=local

EOF

# 添加邮件配置
if [ "$ENV_TYPE" = "production" ] && [ -n "$mail_host" ]; then
    cat >> "$env_file" << EOF
# 邮件配置 - 生产环境SMTP设置
MAIL_MAILER=smtp
MAIL_HOST=$mail_host
MAIL_PORT=${mail_port:-587}
MAIL_USERNAME=$mail_username
MAIL_PASSWORD=$mail_password
MAIL_ENCRYPTION=tls
MAIL_FROM_ADDRESS="noreply@your-domain.com"
MAIL_FROM_NAME="\${APP_NAME}"

EOF
else
    cat >> "$env_file" << EOF
# 邮件配置 - $([ "$ENV_TYPE" = "development" ] && echo "开发环境使用日志" || echo "生产环境SMTP设置")
MAIL_MAILER=$([ "$ENV_TYPE" = "development" ] && echo "log" || echo "smtp")
$([ "$ENV_TYPE" = "production" ] && cat << PROD_MAIL
MAIL_HOST=your-smtp-host.com
MAIL_PORT=587
MAIL_USERNAME=your-email@domain.com
MAIL_PASSWORD=your-email-password-change-this
MAIL_ENCRYPTION=tls
PROD_MAIL
)
MAIL_FROM_ADDRESS="$([ "$ENV_TYPE" = "development" ] && echo "dev@knowledge-base.local" || echo "noreply@your-domain.com")"
MAIL_FROM_NAME="\${APP_NAME}"

EOF
fi

# 添加Meilisearch配置
cat >> "$env_file" << EOF
# Meilisearch配置 - 使用Docker容器名称进行服务间通信
SCOUT_DRIVER=meilisearch
MEILISEARCH_HOST=http://meilisearch:7700
MEILISEARCH_KEY=$meilisearch_key

# 文档转换配置
DOCUMENT_CONVERSION_DRIVER=pandoc
PANDOC_PATH=/usr/bin/pandoc
CONVERSION_TIMEOUT=300
CONVERSION_QUEUE=documents
CONVERSION_RETRY_TIMES=3
CONVERSION_RETRY_DELAY=60

# Markdown配置
MARKDOWN_RENDERER=commonmark
MARKDOWN_SANITIZE=true
MARKDOWN_PREVIEW_LENGTH=500
MARKDOWN_MAX_FILE_SIZE=10485760

# 存储配置
DOCUMENTS_DISK=documents
MARKDOWN_DISK=markdown
STORAGE_ORGANIZE_BY_DATE=true
EOF

# 添加开发环境特定配置
if [ "$ENV_TYPE" = "development" ]; then
    cat >> "$env_file" << EOF

# 开发工具配置
TELESCOPE_ENABLED=true
DEBUGBAR_ENABLED=true
VITE_APP_NAME="\${APP_NAME}"

# 开发环境特定配置
PHP_IDE_CONFIG=serverName=knowledge-base-dev
XDEBUG_MODE=develop,debug
XDEBUG_CONFIG=client_host=host.docker.internal client_port=9003
EOF
fi

echo -e "${GREEN}✓ 环境配置文件已创建: $env_file${NC}"

# 创建.env符号链接
if [ "$FORCE" = true ] || [ ! -f ".env" ]; then
    ln -sf "$env_file" .env
    echo -e "${GREEN}✓ 已创建 .env 符号链接指向 $env_file${NC}"
fi

# 创建存储目录
echo ""
echo "创建存储目录..."
echo "-----------------------------------"

if [ "$ENV_TYPE" = "development" ]; then
    storage_dirs=(
        "storage/dev/mysql"
        "storage/dev/redis"
        "storage/dev/meilisearch"
        "storage/dev/app"
        "storage/dev/app/private/documents"
        "storage/dev/app/public"
        "storage/dev/logs"
        "storage/dev/logs/app"
        "storage/dev/logs/queue"
    )
else
    storage_dirs=(
        "storage/mysql"
        "storage/redis"
        "storage/meilisearch"
        "storage/app"
        "storage/app/private/documents"
        "storage/app/public"
        "storage/logs"
        "storage/logs/app"
        "storage/logs/queue"
    )
fi

for dir in "${storage_dirs[@]}"; do
    if [ ! -d "$dir" ]; then
        mkdir -p "$dir"
        echo -e "${GREEN}✓ 创建目录: $dir${NC}"
    else
        echo -e "${YELLOW}目录已存在: $dir${NC}"
    fi
done

# 设置目录权限
echo ""
echo "设置目录权限..."
echo "-----------------------------------"

# Laravel需要写入权限的目录
laravel_dirs=(
    "storage"
    "bootstrap/cache"
)

for dir in "${laravel_dirs[@]}"; do
    if [ -d "$dir" ]; then
        chmod -R 775 "$dir"
        echo -e "${GREEN}✓ 设置权限: $dir${NC}"
    fi
done

# 显示配置摘要
echo ""
echo "==================================="
echo "配置摘要"
echo "==================================="

echo "环境类型: $ENV_TYPE"
echo "配置文件: $env_file"
echo "Compose文件: $compose_file"
echo "应用名称: $app_name"
echo "应用URL: $app_url"
echo "数据库名: $db_name"
echo "数据库用户: $db_user"
echo "APP_KEY: ${app_key:0:20}..."
echo "Meilisearch密钥: ${meilisearch_key:0:20}..."

echo ""
echo "==================================="
echo "下一步操作"
echo "==================================="

echo "1. 验证环境配置:"
echo "   ./docker/validate-env.sh"
echo ""
echo "2. 启动Docker服务:"
if [ "$ENV_TYPE" = "development" ]; then
    echo "   docker-compose -f docker-compose.dev.yml up -d"
else
    echo "   docker-compose up -d"
fi
echo ""
echo "3. 测试网络连接:"
echo "   ./docker/test-network.sh"
echo ""
echo "4. 初始化应用:"
echo "   docker exec knowledge_base_app php artisan migrate"
echo "   docker exec knowledge_base_app php artisan db:seed"

echo ""
echo -e "${GREEN}✓ 环境配置完成！${NC}"