#!/usr/bin/env bash

# Prometheus Configuration Generator
# Interactive script to generate Prometheus configurations
# Last Updated: January 2025

set -euo pipefail

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

# Script directory
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
TEMPLATES_DIR="$(dirname "$SCRIPT_DIR")/templates"
OUTPUT_FILE="prometheus-config.yml"

# Print colored output
print_info() { echo -e "${BLUE}ℹ${NC} $1"; }
print_success() { echo -e "${GREEN}✓${NC} $1"; }
print_warning() { echo -e "${YELLOW}⚠${NC} $1"; }
print_error() { echo -e "${RED}✗${NC} $1"; }

# Print header
print_header() {
    echo ""
    echo "═══════════════════════════════════════════════════════════════"
    echo "   Prometheus Configuration Generator"
    echo "═══════════════════════════════════════════════════════════════"
    echo ""
}

# Ask for user input
ask_question() {
    local question="$1"
    local var_name="$2"
    echo -e "${BLUE}?${NC} $question"
    read -r "$var_name"
}

# Ask yes/no question
ask_yes_no() {
    local question="$1"
    local response
    echo -e "${BLUE}?${NC} $question (y/n)"
    read -r response
    [[ "$response" =~ ^[Yy]$ ]]
}

# Select environment
select_environment() {
    echo ""
    print_info "Select deployment environment:"
    echo "  1) Kubernetes"
    echo "  2) Docker / Docker Swarm"
    echo "  3) Node Exporter (VMs/Bare Metal)"
    echo "  4) Custom (start from scratch)"
    echo -n "Choice [1-4]: "
    read -r env_choice

    case $env_choice in
        1) ENVIRONMENT="kubernetes" ;;
        2) ENVIRONMENT="docker" ;;
        3) ENVIRONMENT="node-exporter" ;;
        4) ENVIRONMENT="custom" ;;
        *) print_error "Invalid choice"; exit 1 ;;
    esac

    print_success "Selected: $ENVIRONMENT"
}

# Select service discovery
select_service_discovery() {
    echo ""
    print_info "Select service discovery method(s):"
    echo "  1) Static configuration"
    echo "  2) Kubernetes SD"
    echo "  3) Consul SD"
    echo "  4) DNS SD"
    echo "  5) File SD"
    echo "  6) EC2 SD (AWS)"
    echo -n "Choice [1-6] (comma-separated for multiple): "
    read -r sd_choice

    SERVICE_DISCOVERY=()
    IFS=',' read -ra CHOICES <<< "$sd_choice"
    for choice in "${CHOICES[@]}"; do
        case $choice in
            1) SERVICE_DISCOVERY+=("static") ;;
            2) SERVICE_DISCOVERY+=("kubernetes") ;;
            3) SERVICE_DISCOVERY+=("consul") ;;
            4) SERVICE_DISCOVERY+=("dns") ;;
            5) SERVICE_DISCOVERY+=("file") ;;
            6) SERVICE_DISCOVERY+=("ec2") ;;
            *) print_warning "Invalid choice: $choice" ;;
        esac
    done

    print_success "Selected: ${SERVICE_DISCOVERY[*]}"
}

# Select alert rules
select_alert_rules() {
    echo ""
    print_info "Select alert rule sets to include:"

    ALERT_RULES=()

    if ask_yes_no "Include infrastructure alerts (CPU, memory, disk)?"; then
        ALERT_RULES+=("infrastructure")
    fi

    if ask_yes_no "Include container alerts?"; then
        ALERT_RULES+=("container")
    fi

    if ask_yes_no "Include application alerts?"; then
        ALERT_RULES+=("application")
    fi

    if [[ "$ENVIRONMENT" == "kubernetes" ]] && ask_yes_no "Include Kubernetes alerts?"; then
        ALERT_RULES+=("kubernetes")
    fi

    if ask_yes_no "Include database alerts?"; then
        ALERT_RULES+=("database")
    fi

    print_success "Selected alert rules: ${ALERT_RULES[*]:-none}"
}

# Select recording rules
select_recording_rules() {
    echo ""
    print_info "Select recording rule sets to include:"

    RECORDING_RULES=()

    if ask_yes_no "Include aggregation rules?"; then
        RECORDING_RULES+=("aggregation")
    fi

    if ask_yes_no "Include SLO/SLI rules?"; then
        RECORDING_RULES+=("slo")
    fi

    if ask_yes_no "Include rate calculation rules?"; then
        RECORDING_RULES+=("rate")
    fi

    print_success "Selected recording rules: ${RECORDING_RULES[*]:-none}"
}

# Generate configuration
generate_config() {
    echo ""
    print_info "Generating Prometheus configuration..."

    # Start with base template
    case $ENVIRONMENT in
        kubernetes)
            cp "$TEMPLATES_DIR/kubernetes-monitoring/prometheus.yml" "$OUTPUT_FILE"
            ;;
        docker)
            cp "$TEMPLATES_DIR/docker-monitoring/prometheus.yml" "$OUTPUT_FILE"
            ;;
        node-exporter)
            cp "$TEMPLATES_DIR/node-exporter/prometheus.yml" "$OUTPUT_FILE"
            ;;
        custom)
            cat > "$OUTPUT_FILE" <<EOF
# Prometheus Configuration
# Generated: $(date)

global:
  scrape_interval: 15s
  evaluation_interval: 15s
  external_labels:
    cluster: 'production'

alerting:
  alertmanagers:
    - static_configs:
        - targets:
            - 'alertmanager:9093'

rule_files:
  - '/etc/prometheus/rules/alerting/*.yml'
  - '/etc/prometheus/rules/recording/*.yml'

scrape_configs:
  - job_name: 'prometheus'
    static_configs:
      - targets: ['localhost:9090']

EOF
            ;;
    esac

    print_success "Base configuration created"

    # Copy alert rules
    if [ ${#ALERT_RULES[@]} -gt 0 ]; then
        echo ""
        print_info "Copying alert rules..."
        mkdir -p alerting-rules
        for rule in "${ALERT_RULES[@]}"; do
            cp "$TEMPLATES_DIR/alerting-rules/${rule}-alerts.yml" "alerting-rules/"
            print_success "  - ${rule}-alerts.yml"
        done
    fi

    # Copy recording rules
    if [ ${#RECORDING_RULES[@]} -gt 0 ]; then
        echo ""
        print_info "Copying recording rules..."
        mkdir -p recording-rules
        for rule in "${RECORDING_RULES[@]}"; do
            cp "$TEMPLATES_DIR/recording-rules/${rule}-rules.yml" "recording-rules/"
            print_success "  - ${rule}-rules.yml"
        done
    fi

    # Copy service discovery examples
    if [ ${#SERVICE_DISCOVERY[@]} -gt 0 ]; then
        echo ""
        print_info "Copying service discovery examples..."
        mkdir -p service-discovery
        for sd in "${SERVICE_DISCOVERY[@]}"; do
            if [ -f "$TEMPLATES_DIR/service-discovery/${sd}-sd.yml" ]; then
                cp "$TEMPLATES_DIR/service-discovery/${sd}-sd.yml" "service-discovery/"
                print_success "  - ${sd}-sd.yml"
            fi
        done
    fi
}

# Print next steps
print_next_steps() {
    echo ""
    echo "═══════════════════════════════════════════════════════════════"
    print_success "Configuration generated successfully!"
    echo "═══════════════════════════════════════════════════════════════"
    echo ""
    print_info "Files created:"
    echo "  - $OUTPUT_FILE (main configuration)"
    [ ${#ALERT_RULES[@]} -gt 0 ] && echo "  - alerting-rules/ (alert rules)"
    [ ${#RECORDING_RULES[@]} -gt 0 ] && echo "  - recording-rules/ (recording rules)"
    [ ${#SERVICE_DISCOVERY[@]} -gt 0 ] && echo "  - service-discovery/ (SD examples)"
    echo ""
    print_info "Next steps:"
    echo ""
    echo "1. Review and customize the configuration:"
    echo "   \$ cat $OUTPUT_FILE"
    echo ""
    echo "2. Validate the configuration:"
    echo "   \$ promtool check config $OUTPUT_FILE"
    echo ""
    if [ ${#ALERT_RULES[@]} -gt 0 ]; then
        echo "3. Validate alert rules:"
        echo "   \$ promtool check rules alerting-rules/*.yml"
        echo ""
    fi
    if [ ${#RECORDING_RULES[@]} -gt 0 ]; then
        echo "4. Validate recording rules:"
        echo "   \$ promtool check rules recording-rules/*.yml"
        echo ""
    fi
    echo "5. Deploy to Prometheus:"
    case $ENVIRONMENT in
        kubernetes)
            echo "   \$ kubectl create configmap prometheus-config \\"
            echo "       --from-file=$OUTPUT_FILE \\"
            echo "       --namespace=monitoring"
            ;;
        docker)
            echo "   \$ docker run -d -p 9090:9090 \\"
            echo "       -v \$(pwd)/$OUTPUT_FILE:/etc/prometheus/prometheus.yml \\"
            echo "       prom/prometheus"
            ;;
        *)
            echo "   \$ cp $OUTPUT_FILE /etc/prometheus/prometheus.yml"
            echo "   \$ systemctl reload prometheus"
            ;;
    esac
    echo ""
    echo "6. Reload Prometheus:"
    echo "   \$ curl -X POST http://localhost:9090/-/reload"
    echo ""
}

# Main execution
main() {
    print_header

    # Check if templates directory exists
    if [ ! -d "$TEMPLATES_DIR" ]; then
        print_error "Templates directory not found: $TEMPLATES_DIR"
        exit 1
    fi

    # Interactive selection
    select_environment
    select_service_discovery
    select_alert_rules
    select_recording_rules

    # Generate configuration
    generate_config

    # Print next steps
    print_next_steps
}

# Run main
main "$@"
