#!/bin/bash
# ==================================================
# OCDP Backend - Docker Compose 快速启动脚本
# ==================================================

set -e

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

# 打印带颜色的消息
print_info() {
    echo -e "${BLUE}ℹ️  $1${NC}"
}

print_success() {
    echo -e "${GREEN}✅ $1${NC}"
}

print_warning() {
    echo -e "${YELLOW}⚠️  $1${NC}"
}

print_error() {
    echo -e "${RED}❌ $1${NC}"
}

print_header() {
    echo ""
    echo -e "${BLUE}========================================${NC}"
    echo -e "${BLUE}$1${NC}"
    echo -e "${BLUE}========================================${NC}"
    echo ""
}

# 检查 Docker
check_docker() {
    if ! command -v docker &> /dev/null; then
        print_error "Docker 未安装，请先安装 Docker"
        echo "访问: https://docs.docker.com/get-docker/"
        exit 1
    fi
    
    if ! docker compose version &> /dev/null; then
        print_error "Docker Compose 未安装，请先安装 Docker Compose V2"
        echo "访问: https://docs.docker.com/compose/install/"
        exit 1
    fi
    
    print_success "Docker 环境检查通过"
}

# 检查环境变量文件
check_env_file() {
    if [ ! -f .env ]; then
        print_warning ".env 文件不存在，正在从 env.example 创建..."
        cp env.example .env
        print_success ".env 文件已创建"
        print_warning "请编辑 .env 文件，配置必要的环境变量（特别是生产环境的密钥）"
        echo ""
        read -p "按回车键继续..."
    else
        print_success ".env 文件已存在"
    fi
}

# 显示菜单
show_menu() {
    print_header "OCDP Backend - Docker Compose 快速启动"
    
    echo "请选择运行模式:"
    echo ""
    echo "  1) Mock 模式 (无需数据库，快速测试)"
    echo "  2) 生产模式 (完整功能，需要数据库)"
    echo "  3) 开发模式 (热重载，需要数据库)"
    echo "  4) 查看服务状态"
    echo "  5) 查看日志"
    echo "  6) 停止所有服务"
    echo "  7) 启动 pgAdmin (数据库管理)"
    echo "  0) 退出"
    echo ""
}

# 启动 Mock 模式
start_mock() {
    print_header "启动 Mock 模式"
    print_info "正在启动服务..."
    
    docker compose --profile mock up -d
    
    echo ""
    print_success "Mock 模式启动成功！"
    echo ""
    print_info "服务访问地址:"
    echo "  📍 API:    http://localhost:8080/api/v1"
    echo "  📍 Health: http://localhost:8080/health"
    echo ""
    print_info "查看日志: docker compose logs -f backend-mock"
    print_info "停止服务: docker compose down"
}

# 启动生产模式
start_production() {
    print_header "启动生产模式"
    print_info "正在启动数据库和后端服务..."
    
    docker compose --profile production up -d
    
    echo ""
    print_info "等待服务就绪..."
    sleep 5
    
    # 检查服务健康
    if curl -sf http://localhost:8080/health > /dev/null 2>&1; then
        print_success "生产模式启动成功！"
    else
        print_warning "服务正在启动中，请稍候..."
    fi
    
    echo ""
    print_info "服务访问地址:"
    echo "  📍 API:    http://localhost:8080/api/v1"
    echo "  📍 Health: http://localhost:8080/health"
    echo ""
    print_info "数据库信息:"
    echo "  📍 Host: localhost"
    echo "  📍 Port: 5432"
    echo "  📍 Database: ocdp"
    echo ""
    print_info "查看日志: docker compose logs -f backend"
    print_info "停止服务: docker compose down"
}

# 启动开发模式
start_development() {
    print_header "启动开发模式"
    print_info "正在启动开发环境（支持热重载）..."
    
    docker compose -f docker-compose.yml -f docker-compose.dev.yml up -d
    
    echo ""
    print_info "等待服务就绪..."
    sleep 5
    
    print_success "开发模式启动成功！"
    echo ""
    print_info "服务访问地址:"
    echo "  📍 API:    http://localhost:8080/api/v1"
    echo "  📍 Health: http://localhost:8080/health"
    echo ""
    print_info "开发模式特性:"
    echo "  🔥 支持代码热重载（修改代码自动重启）"
    echo "  📂 源代码已挂载到容器"
    echo ""
    print_info "查看日志: docker compose logs -f backend-dev"
    print_info "停止服务: docker compose down"
}

# 查看状态
show_status() {
    print_header "服务状态"
    docker compose ps
}

# 查看日志
show_logs() {
    print_header "查看日志"
    echo "实时查看日志（按 Ctrl+C 退出）..."
    echo ""
    sleep 2
    docker compose logs -f
}

# 停止服务
stop_services() {
    print_header "停止服务"
    print_info "正在停止所有服务..."
    
    docker compose down
    
    print_success "所有服务已停止"
}

# 启动 pgAdmin
start_pgadmin() {
    print_header "启动 pgAdmin"
    print_info "正在启动 pgAdmin..."
    
    docker compose --profile tools up -d pgadmin
    
    echo ""
    print_success "pgAdmin 启动成功！"
    echo ""
    print_info "访问地址: http://localhost:5050"
    print_info "登录信息:"
    echo "  📧 邮箱: ${PGADMIN_EMAIL:-admin@ocdp.local}"
    echo "  🔑 密码: ${PGADMIN_PASSWORD:-change-me}"
    echo ""
    print_info "连接数据库配置:"
    echo "  📍 Host: postgres"
    echo "  📍 Port: 5432"
    echo "  📍 Database: ocdp"
    echo "  📍 Username: postgres"
    echo "  📍 Password: postgres"
}

# 主函数
main() {
    # 获取脚本目录
    SCRIPT_DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"
    cd "$SCRIPT_DIR/.."
    
    # 检查环境
    check_docker
    check_env_file
    
    while true; do
        show_menu
        read -p "请选择 [0-7]: " choice
        
        case $choice in
            1)
                start_mock
                echo ""
                read -p "按回车键返回菜单..."
                ;;
            2)
                start_production
                echo ""
                read -p "按回车键返回菜单..."
                ;;
            3)
                start_development
                echo ""
                read -p "按回车键返回菜单..."
                ;;
            4)
                show_status
                echo ""
                read -p "按回车键返回菜单..."
                ;;
            5)
                show_logs
                ;;
            6)
                stop_services
                echo ""
                read -p "按回车键返回菜单..."
                ;;
            7)
                start_pgadmin
                echo ""
                read -p "按回车键返回菜单..."
                ;;
            0)
                print_info "再见！"
                exit 0
                ;;
            *)
                print_error "无效的选择，请重试"
                sleep 1
                ;;
        esac
    done
}

# 运行主函数
main
