#!/bin/bash
# ============================================================================
# 君鸿卡管系统 - 本地开发快速启动脚本
# ============================================================================
# 使用方法：
#   ./scripts/run-local.sh        # 启动 API 服务
#   ./scripts/run-local.sh worker # 启动 Worker 服务
#   ./scripts/run-local.sh both   # 同时启动 API 和 Worker
# ============================================================================

set -e

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

ENV_FILE=".env.local"

# 检查环境配置文件
check_env() {
    if [ ! -f "$ENV_FILE" ]; then
        echo -e "${RED}[ERROR]${NC} 未找到环境配置文件: $ENV_FILE"
        echo ""
        echo "请先运行环境配置向导："
        echo -e "  ${BLUE}./scripts/setup-env.sh${NC}"
        exit 1
    fi
}

# 加载环境变量
load_env() {
    echo -e "${BLUE}[INFO]${NC} 加载环境变量: $ENV_FILE"
    source "$ENV_FILE"
}

# 创建日志目录
ensure_logs_dir() {
    if [ ! -d "logs" ]; then
        mkdir -p logs
        echo -e "${GREEN}[OK]${NC} 创建日志目录: logs/"
    fi
}

# 启动 API 服务
start_api() {
    echo -e "\n${GREEN}========================================${NC}"
    echo -e "${GREEN}  启动 API 服务${NC}"
    echo -e "${GREEN}========================================${NC}\n"
    go run cmd/api/main.go
}

# 启动 Worker 服务
start_worker() {
    echo -e "\n${GREEN}========================================${NC}"
    echo -e "${GREEN}  启动 Worker 服务${NC}"
    echo -e "${GREEN}========================================${NC}\n"
    go run cmd/worker/main.go
}

# 同时启动两个服务
start_both() {
    echo -e "\n${GREEN}========================================${NC}"
    echo -e "${GREEN}  同时启动 API 和 Worker 服务${NC}"
    echo -e "${GREEN}========================================${NC}\n"
    
    # 后台启动 worker
    go run cmd/worker/main.go &
    WORKER_PID=$!
    echo -e "${GREEN}[OK]${NC} Worker 服务已启动 (PID: $WORKER_PID)"
    
    # 前台启动 api
    trap "kill $WORKER_PID 2>/dev/null" EXIT
    go run cmd/api/main.go
}

# 主流程
main() {
    check_env
    load_env
    ensure_logs_dir
    
    case "${1:-api}" in
        api)
            start_api
            ;;
        worker)
            start_worker
            ;;
        both)
            start_both
            ;;
        *)
            echo "用法: $0 [api|worker|both]"
            echo ""
            echo "  api    - 启动 API 服务（默认）"
            echo "  worker - 启动 Worker 服务"
            echo "  both   - 同时启动 API 和 Worker 服务"
            exit 1
            ;;
    esac
}

main "$@"
