#!/bin/bash

set -e
set -o pipefail

# Get WC_ROOT (where this script and templates live)
WC_ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
export WC_ROOT

# =============================================================================
# HELPER FUNCTIONS
# =============================================================================

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

# Helper functions
print_header() {
    echo -e "\n${BLUE}=== $1 ===${NC}\n"
}

print_info() {
    echo -e "${BLUE}INFO:${NC} $1"
}

print_warning() {
    echo -e "${YELLOW}WARNING:${NC} $1"
}

print_success() {
    echo -e "${GREEN}SUCCESS:${NC} $1"
}

print_error() {
    echo -e "${RED}ERROR:${NC} $1"
}

# Function to prompt for input with default value
prompt_with_default() {
    local prompt="$1"
    local default="$2"
    local current_value="$3"
    local result
    
    if [ -n "${current_value}" ] && [ "${current_value}" != "null" ]; then
        printf "%s [current: %s]: " "${prompt}" "${current_value}" >&2
        read -r result
        if [ -z "${result}" ]; then
            result="${current_value}"
        fi
    elif [ -n "${default}" ]; then
        printf "%s [default: %s]: " "${prompt}" "${default}" >&2
        read -r result
        if [ -z "${result}" ]; then
            result="${default}"
        fi
    else
        printf "%s: " "${prompt}" >&2
        read -r result
        while [ -z "${result}" ]; do
            printf "This value is required. Please enter a value: " >&2
            read -r result
        done
    fi
    
    echo "${result}"
}

# Function to get current config value safely
get_current_config() {
    local key="$1"
    if [ -f "${WC_HOME}/config.yaml" ]; then
        set +e
        result=$(wild-config "${key}" 2>/dev/null)
        set -e
        echo "${result}"
    else
        echo ""
    fi
}

# Function to get current secret value safely
get_current_secret() {
    local key="$1"
    if [ -f "${WC_HOME}/secrets.yaml" ]; then
        set +e
        result=$(wild-secret "${key}" 2>/dev/null)
        set -e
        echo "${result}"
    else
        echo ""
    fi
}

UPDATE=false

# Parse arguments
while [[ $# -gt 0 ]]; do
    case $1 in
        --update)
            UPDATE=true
            shift
            ;;
        -h|--help)
            echo "Usage: $0 [--update]"
            echo ""
            echo "Initialize Wild-Cloud scaffold and basic configuration."
            echo ""
            echo "Options:"
            echo "  --update            Update existing cloud files (overwrite)"
            echo "  -h, --help          Show this help message"
            echo ""
            echo "This script will:"
            echo "  - Initialize the .wildcloud directory structure"
            echo "  - Copy template files to the current directory"
            echo "  - Configure basic settings (email, domains, cluster name)"
            echo ""
            echo "After running this script, use:"
            echo "  - wild-setup-cluster   # Set up Kubernetes cluster (Phases 1-3)"
            echo "  - wild-setup-services  # Install cluster services (Phase 4)"
            exit 0
            ;;
        -*)
            echo "Unknown option $1"
            echo "Usage: $0 [--update]"
            echo "Use --help for full usage information"
            exit 1
            ;;
        *)
            echo "Unexpected argument: $1"
            echo "Usage: $0 [--update]"
            echo "Use --help for full usage information"
            exit 1
            ;;
    esac
done

# Set up cloud directory (WC_HOME is where user's cloud will be)
WC_HOME="$(pwd)"
export WC_HOME

# Template directory (in WC_ROOT, never written to)
TEMPLATE_DIR="${WC_ROOT}/setup/home-scaffold"

if [ ! -d "${TEMPLATE_DIR}" ]; then
    echo "Error: Template directory not found at ${TEMPLATE_DIR}"
    exit 1
fi

# Check if cloud already exists
if [ -d ".wildcloud" ]; then
    echo "Wild-Cloud already exists in this directory."
    echo ""
    read -p "Do you want to update cloud files? (y/N): " -n 1 -r
    echo
    if [[ $REPLY =~ ^[Yy]$ ]]; then
        UPDATE=true
        echo "Updating cloud files..."
    else
        echo "Skipping cloud update."
        echo ""
    fi
else
    # Check if current directory is empty for new cloud
    if [ "${UPDATE}" = false ]; then
        # Check if directory has any files (including hidden files, excluding . and .. and .git)
        if [ -n "$(find . -maxdepth 1 -name ".*" -o -name "*" | grep -v "^\.$" | grep -v "^\.\.$" | grep -v "^\./\.git$" | head -1)" ]; then
            echo "Error: Current directory is not empty"
            echo "Use --update flag to overwrite existing cloud files while preserving other files"
            exit 1
        fi
    fi
    
    echo "Initializing Wild-Cloud in $(pwd)"
    UPDATE=false
fi

# Initialize cloud files if needed
if [ ! -d ".wildcloud" ] || [ "${UPDATE}" = true ]; then
    if [ "${UPDATE}" = true ]; then
        echo "Updating cloud files (preserving existing custom files)"
    else
        echo "Creating cloud files"
    fi

    # Function to copy files and directories
    copy_cloud_files() {
        local src_dir="$1"
        local dest_dir="$2"
        
        # Create destination directory if it doesn't exist
        mkdir -p "${dest_dir}"
        
        # Copy directory structure
        find "${src_dir}" -type d | while read -r src_subdir; do
            rel_path="${src_subdir#${src_dir}}"
            rel_path="${rel_path#/}"  # Remove leading slash if present
            if [ -n "${rel_path}" ]; then
                mkdir -p "${dest_dir}/${rel_path}"
            fi
        done
        
        # Copy files
        find "${src_dir}" -type f | while read -r src_file; do
            rel_path="${src_file#${src_dir}}"
            rel_path="${rel_path#/}"  # Remove leading slash if present
            dest_file="${dest_dir}/${rel_path}"
            
            # Ensure destination directory exists
            dest_file_dir=$(dirname "${dest_file}")
            mkdir -p "${dest_file_dir}"
            
            if [ "${UPDATE}" = true ] && [ -f "${dest_file}" ]; then
                echo "Updating: ${rel_path}"
            else
                echo "Creating: ${rel_path}"
            fi
            
            cp "${src_file}" "${dest_file}"
        done
    }

    # Copy cloud files to current directory
    copy_cloud_files "${TEMPLATE_DIR}" "."
    
    echo ""
    echo "Wild-Cloud initialized successfully!"
    echo ""
fi

# =============================================================================
# BASIC CONFIGURATION
# =============================================================================

# Configure basic settings
if [ ! -f "${WC_HOME}/config.yaml" ] || [ -z "$(get_current_config "operator.email")" ]; then
    print_header "Basic Configuration"
    
    # Detect current network for suggestions
    CURRENT_IP=$(ip route get 8.8.8.8 | awk '{print $7; exit}' 2>/dev/null || echo "192.168.1.100")
    GATEWAY_IP=$(ip route | grep default | awk '{print $3; exit}' 2>/dev/null || echo "192.168.1.1")
    SUBNET_PREFIX=$(echo "${CURRENT_IP}" | cut -d. -f1-3)
    print_info "Detected network: ${SUBNET_PREFIX}.x (gateway: ${GATEWAY_IP})"
    
    echo "This will configure basic settings for your wild-cloud deployment."
    echo ""
    
    # Basic Information
    current_email=$(get_current_config "operator.email")
    email=$(prompt_with_default "Your email address (for Let's Encrypt certificates)" "" "${current_email}")
    wild-config-set "operator.email" "${email}"

    # Domain Configuration
    current_base_domain=$(get_current_config "cloud.baseDomain")
    base_domain=$(prompt_with_default "Your base domain name (e.g., example.com)" "" "${current_base_domain}")
    wild-config-set "cloud.baseDomain" "${base_domain}"

    current_domain=$(get_current_config "cloud.domain")
    domain=$(prompt_with_default "Your public cloud domain" "cloud.${base_domain}" "${current_domain}")
    wild-config-set "cloud.domain" "${domain}"

    current_internal_domain=$(get_current_config "cloud.internalDomain")
    internal_domain=$(prompt_with_default "Your internal cloud domain" "internal.${domain}" "${current_internal_domain}")
    wild-config-set "cloud.internalDomain" "${internal_domain}"

    # Derive cluster name from domain
    cluster_name=$(echo "${domain}" | tr '.' '-' | tr '[:upper:]' '[:lower:]')
    wild-config-set "cluster.name" "${cluster_name}"
    print_info "Set cluster name to: ${cluster_name}"
    
    print_success "Basic configuration completed"
    echo ""
fi

# =============================================================================
# COMPLETION
# =============================================================================

print_header "Wild-Cloud Scaffold Setup Complete!"

print_success "Cloud scaffold initialized successfully!"
echo ""

print_info "Configuration files:"
echo "  - ${WC_HOME}/config.yaml"
echo "  - ${WC_HOME}/secrets.yaml"

echo ""
print_info "Next steps:"
echo "  1. Set up your Kubernetes cluster:"
echo "     wild-setup-cluster"
echo ""
echo "  2. Install cluster services:"
echo "     wild-setup-services"
echo ""
echo "Or run the complete setup:"
echo "  wild-setup"

print_success "Ready for cluster setup!"