#!/bin/bash

# Configuration Builder Script
# Combines base configurations and feature configurations into a complete config.toml
# Usage: ./build-config.sh [environment] [output_file]
# Example: ./build-config.sh dev config.toml

set -e

# Default values
ENVIRONMENT="${1:-dev}"
OUTPUT_FILE="${2:-config.toml}"
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
CONFIG_DIR="$(dirname "$SCRIPT_DIR")"
PROJECT_ROOT="$(dirname "$CONFIG_DIR")"

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

# Logging functions
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"
}

# Check if environment is valid
check_environment() {
    local env="$1"
    case "$env" in
        dev|prod|example)
            return 0
            ;;
        *)
            log_error "Invalid environment: $env"
            log_error "Valid environments: dev, prod, example"
            exit 1
            ;;
    esac
}

# Check if required tools are installed
check_dependencies() {
    local missing_tools=()

    if ! command -v toml &> /dev/null; then
        missing_tools+=("toml")
    fi

    if [ ${#missing_tools[@]} -ne 0 ]; then
        log_warning "Missing optional tools: ${missing_tools[*]}"
        log_warning "For better TOML validation, install: cargo install toml-cli"
    fi
}

# Create temporary directory for processing
create_temp_dir() {
    TEMP_DIR=$(mktemp -d)
    trap "rm -rf $TEMP_DIR" EXIT
    log_info "Created temporary directory: $TEMP_DIR"
}

# Copy base configuration
copy_base_config() {
    local env="$1"
    local base_file="$CONFIG_DIR/base/${env}.toml"

    if [ -f "$base_file" ]; then
        log_info "Copying base configuration: $base_file"
        cp "$base_file" "$TEMP_DIR/base.toml"
    else
        log_error "Base configuration not found: $base_file"
        exit 1
    fi
}

# Find and copy feature configurations
copy_feature_configs() {
    local env="$1"
    local features_dir="$CONFIG_DIR/features"

    if [ ! -d "$features_dir" ]; then
        log_error "Features directory not found: $features_dir"
        exit 1
    fi

    log_info "Copying feature configurations for environment: $env"

    # Create features directory in temp
    mkdir -p "$TEMP_DIR/features"

    # Find all feature directories
    for feature_dir in "$features_dir"/*; do
        if [ -d "$feature_dir" ]; then
            local feature_name=$(basename "$feature_dir")
            local feature_file="$feature_dir/${env}.toml"

            if [ -f "$feature_file" ]; then
                log_info "  Found feature: $feature_name"
                cp "$feature_file" "$TEMP_DIR/features/${feature_name}.toml"
            else
                log_warning "  Feature configuration not found: $feature_file"
            fi
        fi
    done
}

# Merge configurations using a simple approach
merge_configs() {
    local output="$1"

    log_info "Merging configurations..."

    # Start with base configuration
    cat "$TEMP_DIR/base.toml" > "$output"

    # Add a separator comment
    echo "" >> "$output"
    echo "# =================================" >> "$output"
    echo "# Feature Configurations" >> "$output"
    echo "# =================================" >> "$output"
    echo "" >> "$output"

    # Append each feature configuration
    for feature_file in "$TEMP_DIR/features"/*.toml; do
        if [ -f "$feature_file" ]; then
            local feature_name=$(basename "$feature_file" .toml)
            echo "" >> "$output"
            echo "# ${feature_name} Feature Configuration" >> "$output"
            echo "# =================================" >> "$output"
            cat "$feature_file" >> "$output"
            echo "" >> "$output"
        fi
    done

    # Add build information
    echo "" >> "$output"
    echo "# Build Information" >> "$output"
    echo "# =================================" >> "$output"
    echo "[build_info]" >> "$output"
    echo "environment = \"$ENVIRONMENT\"" >> "$output"
    echo "build_time = \"$(date -u +%Y-%m-%dT%H:%M:%SZ)\"" >> "$output"
    echo "build_script = \"$(basename "$0")\"" >> "$output"
    echo "config_version = \"1.0.0\"" >> "$output"
}

# Validate the generated configuration
validate_config() {
    local config_file="$1"

    log_info "Validating configuration..."

    # Basic validation - check if file exists and is not empty
    if [ ! -f "$config_file" ]; then
        log_error "Configuration file not found: $config_file"
        return 1
    fi

    if [ ! -s "$config_file" ]; then
        log_error "Configuration file is empty: $config_file"
        return 1
    fi

    # Advanced validation with toml tool if available
    if command -v toml &> /dev/null; then
        if toml get "$config_file" > /dev/null 2>&1; then
            log_success "TOML syntax validation passed"
        else
            log_error "TOML syntax validation failed"
            return 1
        fi
    else
        log_warning "TOML validation tool not available, skipping syntax check"
    fi

    # Check for required sections
    local required_sections=("server" "database" "app")
    for section in "${required_sections[@]}"; do
        if grep -q "^\[${section}\]" "$config_file"; then
            log_info "  Required section found: [$section]"
        else
            log_warning "  Required section missing: [$section]"
        fi
    done

    return 0
}

# Generate summary of the build
generate_summary() {
    local config_file="$1"

    log_info "Configuration build summary:"
    log_info "  Environment: $ENVIRONMENT"
    log_info "  Output file: $config_file"
    log_info "  File size: $(du -h "$config_file" | cut -f1)"
    log_info "  Line count: $(wc -l < "$config_file")"

    # Count features
    local feature_count=$(grep -c "# .* Feature Configuration" "$config_file" 2>/dev/null || echo "0")
    log_info "  Features included: $feature_count"

    # List features
    if [ "$feature_count" -gt 0 ]; then
        log_info "  Feature list:"
        grep "# .* Feature Configuration" "$config_file" | sed 's/# \(.*\) Feature Configuration/    - \1/' || true
    fi
}

# Backup existing configuration
backup_existing_config() {
    local config_file="$1"

    if [ -f "$config_file" ]; then
        local backup_file="${config_file}.backup.$(date +%Y%m%d_%H%M%S)"
        log_info "Backing up existing configuration to: $backup_file"
        cp "$config_file" "$backup_file"
    fi
}

# Show help
show_help() {
    cat << EOF
Configuration Builder Script

USAGE:
    $0 [ENVIRONMENT] [OUTPUT_FILE]

ARGUMENTS:
    ENVIRONMENT    Target environment (dev, prod, example). Default: dev
    OUTPUT_FILE    Output configuration file. Default: config.toml

EXAMPLES:
    $0                          # Build dev config to config.toml
    $0 prod                     # Build prod config to config.toml
    $0 dev config.dev.toml      # Build dev config to config.dev.toml
    $0 prod config.prod.toml    # Build prod config to config.prod.toml

DESCRIPTION:
    This script combines base configurations and feature-specific configurations
    into a complete TOML configuration file for the specified environment.

    The script looks for:
    - Base configuration: config/base/[environment].toml
    - Feature configurations: config/features/[feature]/[environment].toml

ENVIRONMENT VARIABLES:
    CONFIG_DEBUG=1             Enable debug output
    CONFIG_NO_BACKUP=1         Skip backup of existing configuration
    CONFIG_VALIDATE_ONLY=1     Only validate, don't build

EOF
}

# Main function
main() {
    # Parse arguments
    if [ "$1" = "-h" ] || [ "$1" = "--help" ]; then
        show_help
        exit 0
    fi

    # Enable debug if requested
    if [ "${CONFIG_DEBUG:-0}" = "1" ]; then
        set -x
    fi

    log_info "Starting configuration build process..."
    log_info "Environment: $ENVIRONMENT"
    log_info "Output file: $OUTPUT_FILE"

    # Check environment
    check_environment "$ENVIRONMENT"

    # Check dependencies
    check_dependencies

    # Create temporary directory
    create_temp_dir

    # Copy base configuration
    copy_base_config "$ENVIRONMENT"

    # Copy feature configurations
    copy_feature_configs "$ENVIRONMENT"

    # Backup existing configuration if not disabled
    if [ "${CONFIG_NO_BACKUP:-0}" != "1" ]; then
        backup_existing_config "$OUTPUT_FILE"
    fi

    # If validation only, validate temp config and exit
    if [ "${CONFIG_VALIDATE_ONLY:-0}" = "1" ]; then
        merge_configs "$TEMP_DIR/validation.toml"
        validate_config "$TEMP_DIR/validation.toml"
        log_success "Configuration validation completed"
        exit 0
    fi

    # Merge configurations
    merge_configs "$OUTPUT_FILE"

    # Validate the generated configuration
    if ! validate_config "$OUTPUT_FILE"; then
        log_error "Configuration validation failed"
        exit 1
    fi

    # Generate summary
    generate_summary "$OUTPUT_FILE"

    log_success "Configuration build completed successfully!"
    log_info "Configuration file: $OUTPUT_FILE"
}

# Run main function
main "$@"
