#!/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

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

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

# Usage function
usage() {
    echo "Usage: wild-cluster-config-generate [options]"
    echo ""
    echo "Generate initial Talos cluster configuration using talosctl gen config."
    echo ""
    echo "Options:"
    echo "  -h, --help          Show this help message"
    echo "  --force             Force regeneration even if config already exists"
    echo ""
    echo "This script will:"
    echo "  - Generate initial cluster secrets and configurations"
    echo "  - Create base controlplane.yaml and worker.yaml templates"
    echo "  - Set up the foundation for node-specific machine configs"
    echo ""
    echo "Requirements:"
    echo "  - Must be run from a wild-cloud directory"
    echo "  - Cluster name and VIP must be configured"
    echo "  - talosctl must be available in PATH"
}

# Parse arguments
FORCE=false
while [[ $# -gt 0 ]]; do
    case $1 in
        -h|--help)
            usage
            exit 0
            ;;
        --force)
            FORCE=true
            shift
            ;;
        -*)
            echo "Unknown option $1"
            usage
            exit 1
            ;;
        *)
            echo "Unexpected argument: $1"
            usage
            exit 1
            ;;
    esac
done

# Check if we're in a wild-cloud directory
if [ ! -d ".wildcloud" ]; then
    print_error "You must run this script from a wild-cloud directory"
    print_info "Run 'wild-setup' or 'wild-init' first to initialize a wild-cloud project"
    exit 1
fi

# Check if talosctl is available
if ! command -v talosctl >/dev/null 2>&1; then
    print_error "talosctl not found in PATH"
    print_info "Please install talosctl to generate cluster configurations"
    exit 1
fi

# =============================================================================
# CLUSTER CONFIGURATION GENERATION
# =============================================================================

print_header "Talos Cluster Configuration Generation"

# Ensure required directories exist
NODE_SETUP_DIR="${WC_HOME}/setup/cluster-nodes"
mkdir -p "${NODE_SETUP_DIR}/generated"

# Check if cluster configuration already exists
if [ -f "${NODE_SETUP_DIR}/generated/secrets.yaml" ] && [ "$FORCE" = false ]; then
    print_success "Cluster configuration already exists"
    print_info "Generated files:"
    for file in "${NODE_SETUP_DIR}/generated"/*.yaml; do
        if [ -f "$file" ]; then
            print_info "  - $(basename "$file")"
        fi
    done
    echo ""
    print_info "Use --force to regenerate cluster configuration"
    exit 0
fi

# Get cluster configuration
CLUSTER_NAME=$(get_current_config "cluster.name")
VIP=$(get_current_config "cluster.nodes.control.vip")

# Validate required configuration
if [ -z "$CLUSTER_NAME" ] || [ "$CLUSTER_NAME" = "null" ]; then
    print_error "Cluster name not configured"
    print_info "Please run 'wild-setup' first to configure cluster.name"
    exit 1
fi

if [ -z "$VIP" ] || [ "$VIP" = "null" ]; then
    print_error "Control plane VIP not configured"
    print_info "Please run 'wild-setup' first to configure cluster.nodes.control.vip"
    exit 1
fi

# Generate cluster configuration
print_info "Generating initial cluster configuration..."
print_info "Cluster name: $CLUSTER_NAME"
print_info "Control plane endpoint: https://$VIP:6443"

if [ "$FORCE" = true ] && [ -d "${NODE_SETUP_DIR}/generated" ]; then
    print_warning "Removing existing cluster configuration..."
    rm -rf "${NODE_SETUP_DIR}/generated"
    mkdir -p "${NODE_SETUP_DIR}/generated"
fi

cd "${NODE_SETUP_DIR}/generated"
talosctl gen config "$CLUSTER_NAME" "https://$VIP:6443"
cd - >/dev/null

# Verify generated files
REQUIRED_FILES=("secrets.yaml" "controlplane.yaml" "worker.yaml" "talosconfig")
MISSING_FILES=()

for file in "${REQUIRED_FILES[@]}"; do
    if [ ! -f "${NODE_SETUP_DIR}/generated/$file" ]; then
        MISSING_FILES+=("$file")
    fi
done

if [ ${#MISSING_FILES[@]} -gt 0 ]; then
    print_error "Some required files were not generated:"
    for file in "${MISSING_FILES[@]}"; do
        print_error "  - $file"
    done
    exit 1
fi

print_success "Cluster configuration generated successfully!"
echo ""
print_info "Generated files:"
for file in "${NODE_SETUP_DIR}/generated"/*.yaml "${NODE_SETUP_DIR}/generated/talosconfig"; do
    if [ -f "$file" ]; then
        filesize=$(du -h "$file" | cut -f1)
        print_success "  ✓ $(basename "$file") ($filesize)"
    fi
done

echo ""
print_info "Configuration details:"
print_info "  - Cluster name: $CLUSTER_NAME"
print_info "  - Control plane endpoint: https://$VIP:6443"
print_info "  - Generated in: ${NODE_SETUP_DIR}/generated/"

echo ""
print_info "Next steps:"
echo "  1. Node-specific machine configs can now be generated"
echo "  2. Use wild-cluster-node-machine-config-generate <ip> for each node"
echo "  3. Apply configs to nodes with talosctl apply-config"
echo "  4. Bootstrap the first control plane node"

print_success "Cluster configuration generation completed!"