#!/bin/bash
# =============================================================================
# RWA Infrastructure - 部署脚本
# =============================================================================
#
# 用法:
#   ./deploy.sh up [组件...]      启动组件 (默认: full)
#   ./deploy.sh down              停止所有组件
#   ./deploy.sh restart [组件...] 重启组件
#   ./deploy.sh logs [组件]       查看日志
#   ./deploy.sh status            查看状态
#   ./deploy.sh health            健康检查
#
# 可用组件:
#   consul    - 服务发现与配置中心
#   jaeger    - 分布式链路追踪
#   loki      - 日志聚合 (包含 promtail)
#   grafana   - 可视化仪表盘
#   prometheus- 指标收集
#   full      - 所有组件
#
# 示例:
#   ./deploy.sh up                    # 启动所有组件
#   ./deploy.sh up consul jaeger      # 只启动 Consul 和 Jaeger
#   ./deploy.sh up loki grafana       # 启动日志和可视化
#   ./deploy.sh logs jaeger           # 查看 Jaeger 日志
#
# =============================================================================

set -e

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
cd "$SCRIPT_DIR"

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

# 配置
COMPOSE_FILE="docker-compose.yml"
ENV_FILE=".env"
ENV_EXAMPLE=".env.example"

# =============================================================================
# 工具函数
# =============================================================================

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"
}

# 检查 .env 文件
check_env() {
    if [ ! -f "$ENV_FILE" ]; then
        if [ -f "$ENV_EXAMPLE" ]; then
            log_info "创建 .env 文件..."
            cp "$ENV_EXAMPLE" "$ENV_FILE"
            log_warning "请检查 .env 文件并配置必要的环境变量"
        else
            log_warning ".env 文件不存在，使用默认配置"
        fi
    fi
}

# 获取 profile 参数
get_profiles() {
    local profiles=""
    if [ $# -eq 0 ] || [ "$1" = "full" ]; then
        profiles="--profile full"
    else
        for component in "$@"; do
            case "$component" in
                consul|jaeger|loki|logging|grafana|prometheus|metrics|tracing)
                    profiles="$profiles --profile $component"
                    ;;
                *)
                    log_error "未知组件: $component"
                    echo "可用组件: consul, jaeger, loki, grafana, prometheus, full"
                    exit 1
                    ;;
            esac
        done
    fi
    echo "$profiles"
}

# =============================================================================
# 命令实现
# =============================================================================

cmd_up() {
    check_env
    local profiles=$(get_profiles "$@")

    log_info "启动基础设施组件..."
    docker compose -f "$COMPOSE_FILE" $profiles up -d

    log_success "组件已启动！"
    echo ""
    cmd_status
}

cmd_down() {
    log_info "停止所有组件..."
    docker compose -f "$COMPOSE_FILE" --profile full down
    log_success "所有组件已停止"
}

cmd_restart() {
    local profiles=$(get_profiles "$@")

    log_info "重启组件..."
    docker compose -f "$COMPOSE_FILE" $profiles restart
    log_success "组件已重启"
}

cmd_logs() {
    local service="${1:-}"
    if [ -n "$service" ]; then
        docker compose -f "$COMPOSE_FILE" logs -f "$service"
    else
        docker compose -f "$COMPOSE_FILE" --profile full logs -f
    fi
}

cmd_status() {
    echo ""
    echo "=========================================="
    echo "  RWA Infrastructure 状态"
    echo "=========================================="
    echo ""

    docker compose -f "$COMPOSE_FILE" --profile full ps --format "table {{.Name}}\t{{.Status}}\t{{.Ports}}"

    echo ""
    echo "=========================================="
    echo "  访问地址"
    echo "=========================================="
    echo ""
    echo "  Consul UI:     http://localhost:${CONSUL_HTTP_PORT:-8500}"
    echo "  Jaeger UI:     http://localhost:${JAEGER_UI_PORT:-16686}"
    echo "  Grafana:       http://localhost:${GRAFANA_PORT:-3030}"
    echo "  Prometheus:    http://localhost:${PROMETHEUS_PORT:-9090}"
    echo "  Loki:          http://localhost:${LOKI_PORT:-3100}"
    echo ""
}

cmd_health() {
    echo ""
    echo "=========================================="
    echo "  健康检查"
    echo "=========================================="
    echo ""

    # Consul
    if curl -s http://localhost:${CONSUL_HTTP_PORT:-8500}/v1/status/leader > /dev/null 2>&1; then
        echo -e "  Consul:     ${GREEN}✓ Healthy${NC}"
    else
        echo -e "  Consul:     ${RED}✗ Unhealthy${NC}"
    fi

    # Jaeger
    if curl -s http://localhost:${JAEGER_UI_PORT:-16686} > /dev/null 2>&1; then
        echo -e "  Jaeger:     ${GREEN}✓ Healthy${NC}"
    else
        echo -e "  Jaeger:     ${RED}✗ Unhealthy${NC}"
    fi

    # Grafana
    if curl -s http://localhost:${GRAFANA_PORT:-3030}/api/health > /dev/null 2>&1; then
        echo -e "  Grafana:    ${GREEN}✓ Healthy${NC}"
    else
        echo -e "  Grafana:    ${RED}✗ Unhealthy${NC}"
    fi

    # Prometheus
    if curl -s http://localhost:${PROMETHEUS_PORT:-9090}/-/healthy > /dev/null 2>&1; then
        echo -e "  Prometheus: ${GREEN}✓ Healthy${NC}"
    else
        echo -e "  Prometheus: ${RED}✗ Unhealthy${NC}"
    fi

    # Loki
    if curl -s http://localhost:${LOKI_PORT:-3100}/ready > /dev/null 2>&1; then
        echo -e "  Loki:       ${GREEN}✓ Healthy${NC}"
    else
        echo -e "  Loki:       ${RED}✗ Unhealthy${NC}"
    fi

    echo ""
}

cmd_help() {
    echo ""
    echo "RWA Infrastructure 部署工具"
    echo ""
    echo "用法: $0 <命令> [参数...]"
    echo ""
    echo "命令:"
    echo "  up [组件...]      启动组件 (默认启动全部)"
    echo "  down              停止所有组件"
    echo "  restart [组件...] 重启组件"
    echo "  logs [组件]       查看日志"
    echo "  status            查看运行状态"
    echo "  health            健康检查"
    echo "  help              显示帮助"
    echo ""
    echo "可用组件:"
    echo "  consul      服务发现与配置中心"
    echo "  jaeger      分布式链路追踪"
    echo "  loki        日志聚合系统"
    echo "  grafana     可视化仪表盘"
    echo "  prometheus  指标收集"
    echo "  full        所有组件 (默认)"
    echo ""
    echo "示例:"
    echo "  $0 up                      # 启动所有组件"
    echo "  $0 up consul jaeger        # 只启动 Consul 和 Jaeger"
    echo "  $0 logs grafana            # 查看 Grafana 日志"
    echo "  $0 health                  # 检查所有组件健康状态"
    echo ""
}

# =============================================================================
# 主入口
# =============================================================================

case "${1:-help}" in
    up)
        shift
        cmd_up "$@"
        ;;
    down)
        cmd_down
        ;;
    restart)
        shift
        cmd_restart "$@"
        ;;
    logs)
        shift
        cmd_logs "$@"
        ;;
    status)
        cmd_status
        ;;
    health)
        cmd_health
        ;;
    help|--help|-h)
        cmd_help
        ;;
    *)
        log_error "未知命令: $1"
        cmd_help
        exit 1
        ;;
esac
