#!/bin/bash

set -e
set -o pipefail


# Parse arguments

UPDATE=false

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

# Initialize Wild Cloud environment

if [ -z "${WC_ROOT}" ]; then
    print "WC_ROOT is not set."
    exit 1
else
    source "${WC_ROOT}/scripts/common.sh"
    init_wild_env
fi

TEMPLATE_DIR="${WC_ROOT}/setup/home-scaffold"

# 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
# =============================================================================

# Basic Information
prompt_if_unset_config "operator.email" "Your email address (for Let's Encrypt certificates)" ""

# Domain Configuration
prompt_if_unset_config "cloud.baseDomain" "Your base domain name (e.g., example.com)" ""

# Get base domain to use as default for cloud domain
base_domain=$(wild-config "cloud.baseDomain")
prompt_if_unset_config "cloud.domain" "Your public cloud domain" "cloud.${base_domain}"

# Get cloud domain to use as default for internal domain
domain=$(wild-config "cloud.domain")
prompt_if_unset_config "cloud.internalDomain" "Your internal cloud domain" "internal.${domain}"

# Derive cluster name from domain if not already set
current_cluster_name=$(get_current_config "cluster.name")
if [ -z "$current_cluster_name" ] || [ "$current_cluster_name" = "null" ]; then
    cluster_name=$(echo "${domain}" | tr '.' '-' | tr '[:upper:]' '[:lower:]')
    wild-config-set "cluster.name" "${cluster_name}"
    print_info "Set cluster name to: ${cluster_name}"
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!"