#!/usr/bin/env bash
set -e

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

# Colors
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
NC='\033[0m' # No Color

usage() {
    echo "Usage: $0 [ENVIRONMENT] [CONFIG_NAME]"
    echo ""
    echo "Update Kubernetes ConfigMaps from YAML files"
    echo ""
    echo "Arguments:"
    echo "  ENVIRONMENT   Target environment: dev or prod (default: dev)"
    echo "  CONFIG_NAME   Specific config to update (optional, updates all if not specified)"
    echo ""
    echo "Available configs:"
    echo "  relay-config     - ZMQ relay configuration"
    echo "  ingestor-config  - CCXT ingestor configuration"
    echo "  flink-config     - Flink job configuration"
    echo ""
    echo "Examples:"
    echo "  $0                          # Update all dev configs"
    echo "  $0 dev                      # Update all dev configs"
    echo "  $0 dev relay-config         # Update only relay-config in dev"
    echo "  $0 prod                     # Update all prod configs"
    echo "  $0 prod flink-config        # Update only flink-config in prod"
    exit 1
}

# Parse arguments
ENV="${1:-dev}"
CONFIG_NAME="${2:-}"

if [[ "$ENV" != "dev" && "$ENV" != "prod" ]]; then
    echo -e "${RED}Error: Environment must be 'dev' or 'prod'${NC}"
    usage
fi

CONFIG_DIR="$ROOT_DIR/deploy/k8s/$ENV/configs"

if [ ! -d "$CONFIG_DIR" ]; then
    echo -e "${RED}Error: Config directory not found: $CONFIG_DIR${NC}"
    exit 1
fi

# Get kubectl context
if [[ "$ENV" == "prod" ]]; then
    CONTEXT=$(kubectl config current-context)
    echo -e "${YELLOW}⚠️  WARNING: Updating PRODUCTION configs!${NC}"
    echo -e "${YELLOW}Current kubectl context: $CONTEXT${NC}"
    read -p "Are you sure you want to continue? (yes/no): " confirm
    if [[ "$confirm" != "yes" ]]; then
        echo "Aborted."
        exit 0
    fi
fi

apply_config() {
    local config_name="$1"
    local config_file="$CONFIG_DIR/$config_name.yaml"

    if [ ! -f "$config_file" ]; then
        echo -e "${RED}✗ Config file not found: $config_file${NC}"
        return 1
    fi

    echo -e "${GREEN}→${NC} Creating/updating ConfigMap $config_name..."
    kubectl create configmap "$config_name" \
        --from-file=config.yaml="$config_file" \
        --dry-run=client -o yaml | kubectl apply -f -
    echo -e "${GREEN}✓${NC} $config_name updated"

    # Optionally restart pods that use this config
    local restart_pods=""
    case "$config_name" in
        relay-config)
            restart_pods="deployment/relay"
            ;;
        ingestor-config)
            restart_pods="deployment/ingestor"
            ;;
        flink-config)
            restart_pods="deployment/flink-jobmanager deployment/flink-taskmanager"
            ;;
    esac

    if [ -n "$restart_pods" ]; then
        echo -e "${YELLOW}  Restarting pods...${NC}"
        kubectl rollout restart $restart_pods 2>/dev/null || echo -e "${YELLOW}  (No pods found to restart)${NC}"
    fi
}

# Update specific config or all configs
if [ -n "$CONFIG_NAME" ]; then
    # Update single config
    apply_config "$CONFIG_NAME"
else
    # Update all configs
    echo -e "${GREEN}Updating all $ENV configs...${NC}"
    echo ""

    CONFIGS=(
        "relay-config"
        "ingestor-config"
        "flink-config"
    )

    FAILED=0
    for config in "${CONFIGS[@]}"; do
        if ! apply_config "$config"; then
            FAILED=$((FAILED + 1))
        fi
    done

    echo ""
    if [ $FAILED -gt 0 ]; then
        echo -e "${YELLOW}⚠️  $FAILED config(s) failed to apply${NC}"
        exit 1
    else
        echo -e "${GREEN}✓ All configs updated successfully${NC}"
    fi
fi
