#!/bin/bash

# Debug version of configuration management script
set -e

# Script configuration
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
CONFIG_DIR="$(dirname "$SCRIPT_DIR")"
PROJECT_ROOT="$(dirname "$CONFIG_DIR")"
BACKUP_DIR="$CONFIG_DIR/backups"
ENVIRONMENTS=("dev" "prod" "example")

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

# Test function
test_basics() {
    echo "=== Configuration Management Debug ==="
    echo "SCRIPT_DIR: $SCRIPT_DIR"
    echo "CONFIG_DIR: $CONFIG_DIR"
    echo "PROJECT_ROOT: $PROJECT_ROOT"
    echo "BACKUP_DIR: $BACKUP_DIR"
    echo ""
}

# List available features
cmd_list_features() {
    log_info "Available features:"

    if [ -d "$CONFIG_DIR/features" ]; then
        for feature_dir in "$CONFIG_DIR/features"/*; do
            if [ -d "$feature_dir" ]; then
                feature_name=$(basename "$feature_dir")
                log_info "  - $feature_name"

                # Show available environments for this feature
                envs=()
                for env in "${ENVIRONMENTS[@]}"; do
                    if [ -f "$feature_dir/$env.toml" ]; then
                        envs+=("$env")
                    fi
                done

                if [ ${#envs[@]} -gt 0 ]; then
                    log_info "    Environments: ${envs[*]}"
                fi
            fi
        done
    else
        log_error "Features directory not found: $CONFIG_DIR/features"
        return 1
    fi
}

# List available environments
cmd_list_environments() {
    log_info "Available environments:"

    for env in "${ENVIRONMENTS[@]}"; do
        log_info "  - $env"

        # Check if base configuration exists
        if [ -f "$CONFIG_DIR/base/$env.toml" ]; then
            log_info "    Base config: ✓"
        else
            log_info "    Base config: ✗"
        fi

        # Count available features
        feature_count=0
        if [ -d "$CONFIG_DIR/features" ]; then
            for feature_dir in "$CONFIG_DIR/features"/*; do
                if [ -d "$feature_dir" ] && [ -f "$feature_dir/$env.toml" ]; then
                    ((feature_count++))
                fi
            done
        fi
        log_info "    Available features: $feature_count"
    done
}

# Build configuration
cmd_build() {
    env="$1"
    output="${2:-config.toml}"

    if [ -z "$env" ]; then
        log_error "Environment required for build command"
        return 1
    fi

    log_info "Building configuration for environment: $env"
    "$SCRIPT_DIR/build-config.sh" "$env" "$output"
}

# Show status
cmd_status() {
    log_info "Configuration system status:"

    # Check directories
    log_info "Directories:"
    for dir in base features scripts; do
        if [ -d "$CONFIG_DIR/$dir" ]; then
            log_info "  $dir: ✓"
        else
            log_info "  $dir: ✗"
        fi
    done

    # Check base configurations
    log_info "Base configurations:"
    for env in "${ENVIRONMENTS[@]}"; do
        if [ -f "$CONFIG_DIR/base/$env.toml" ]; then
            log_info "  $env: ✓"
        else
            log_info "  $env: ✗"
        fi
    done

    # Check features
    log_info "Features:"
    if [ -d "$CONFIG_DIR/features" ]; then
        for feature_dir in "$CONFIG_DIR/features"/*; do
            if [ -d "$feature_dir" ]; then
                feature_name=$(basename "$feature_dir")
                env_count=0
                for env in "${ENVIRONMENTS[@]}"; do
                    if [ -f "$feature_dir/$env.toml" ]; then
                        ((env_count++))
                    fi
                done
                log_info "  $feature_name: $env_count/${#ENVIRONMENTS[@]} environments"
            fi
        done
    fi
}

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

USAGE:
    $0 [COMMAND]

COMMANDS:
    list-features      List available features
    list-environments  List available environments
    build ENV [OUTPUT] Build configuration for environment
    status             Show configuration status
    test               Run basic tests
    help               Show this help message

EXAMPLES:
    $0 list-features
    $0 list-environments
    $0 build dev
    $0 status
    $0 test

EOF
}

# Main function
main() {
    command="$1"
    shift

    case "$command" in
        list-features)
            cmd_list_features
            ;;
        list-environments)
            cmd_list_environments
            ;;
        build)
            cmd_build "$@"
            ;;
        status)
            cmd_status
            ;;
        test)
            test_basics
            cmd_list_features
            echo ""
            cmd_list_environments
            echo ""
            cmd_status
            ;;
        help|"")
            show_help
            ;;
        *)
            log_error "Unknown command: $command"
            show_help
            exit 1
            ;;
    esac
}

# Run main function
main "$@"
