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

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

# Parse arguments
SKIP_INSTALL=false

while [[ $# -gt 0 ]]; do
    case $1 in
        --skip-install)
            SKIP_INSTALL=true
            shift
            ;;
        -h|--help)
            echo "Usage: $0 [options]"
            echo ""
            echo "Install Kubernetes cluster services (Phase 4)."
            echo ""
            echo "Options:"
            echo "  --skip-install      Generate service configs but skip installation"
            echo "  -h, --help          Show this help message"
            echo ""
            echo "This script will:"
            echo "  - Configure DNS and SSL certificate settings"
            echo "  - Configure storage settings (NFS, Docker registry)"
            echo "  - Generate cluster service configurations"
            echo "  - Install core services (MetalLB, Traefik, cert-manager, etc.)"
            echo ""
            echo "Prerequisites:"
            echo "  - Run 'wild-setup-scaffold' to initialize the cloud"
            echo "  - Run 'wild-setup-cluster' to set up cluster infrastructure"
            echo "  - Kubernetes cluster must be running and kubectl configured"
            exit 0
            ;;
        -*)
            echo "Unknown option $1"
            echo "Usage: $0 [options]"
            echo "Use --help for full usage information"
            exit 1
            ;;
        *)
            echo "Unexpected argument: $1"
            echo "Usage: $0 [options]"
            echo "Use --help for full usage information"
            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-scaffold' first to initialize a wild-cloud project"
    exit 1
fi

# Check basic configuration
if [ -z "$(get_current_config "operator.email")" ]; then
    print_error "Basic configuration is missing"
    print_info "Run 'wild-setup-scaffold' first to configure basic settings"
    exit 1
fi

# Check cluster configuration
if [ -z "$(get_current_config "cluster.name")" ]; then
    print_error "Cluster configuration is missing"
    print_info "Run 'wild-setup-cluster' first to configure cluster settings"
    exit 1
fi

print_header "Wild-Cloud Services Setup"
print_info "Installing Kubernetes cluster services (Phase 4)"
echo ""

# =============================================================================
# PHASE 4: Cluster Services Installation
# =============================================================================

print_header "Phase 4: Cluster Services Installation"

# Configure DNS and certificates
if [ -z "$(get_current_config "cluster.certManager.cloudflare.domain")" ]; then
    print_header "DNS and Certificate Configuration"
    echo "For automatic SSL certificates and DNS management, we use Cloudflare."
    echo ""

    base_domain=$(get_current_config "cloud.baseDomain")
    domain=$(get_current_config "cloud.domain")
    
    echo "Is your domain '${base_domain}' registered and managed through Cloudflare? (y/n)"
    read -r use_cloudflare

    if [[ "${use_cloudflare}" =~ ^[Yy]$ ]]; then
        wild-config-set "cluster.certManager.cloudflare.domain" "${domain}"
        
        current_cf_token=$(get_current_secret "cloudflare.token")
        if [ -z "${current_cf_token}" ]; then
            echo ""
            print_info "You'll need a Cloudflare API token with the following permissions:"
            echo "  - Zone:Zone:Read"
            echo "  - Zone:DNS:Edit"
            echo "  - Include:All zones"
            echo ""
            echo "Create one at: https://dash.cloudflare.com/profile/api-tokens"
            echo ""
        fi
        
        cf_token=$(prompt_with_default "Cloudflare API token" "" "${current_cf_token}")
        wild-secret-set "cloudflare.token" "${cf_token}"
    else
        print_warning "You'll need to configure DNS and SSL certificates manually."
        print_info "Consider transferring your domain to Cloudflare for easier management."
    fi
    
    print_success "DNS and certificate configuration completed"
    echo ""
fi

# Configure storage settings
print_header "Storage Configuration"

dns_ip=$(get_current_config "cloud.dns.ip")
internal_domain=$(get_current_config "cloud.internalDomain")

# NFS settings
current_nfs_host=$(get_current_config "cloud.nfs.host")
if [ -z "$current_nfs_host" ] || [ "$current_nfs_host" = "null" ]; then
    nfs_host=$(prompt_with_default "NFS server host" "${dns_ip}" "${current_nfs_host}")
    wild-config-set "cloud.nfs.host" "${nfs_host}"
fi

current_media_path=$(get_current_config "cloud.nfs.mediaPath")
if [ -z "$current_media_path" ] || [ "$current_media_path" = "null" ]; then
    media_path=$(prompt_with_default "NFS media path" "/mnt/storage/media" "${current_media_path}")
    wild-config-set "cloud.nfs.mediaPath" "${media_path}"
fi

current_storage_capacity=$(get_current_config "cloud.nfs.storageCapacity")
if [ -z "$current_storage_capacity" ] || [ "$current_storage_capacity" = "null" ]; then
    storage_capacity=$(prompt_with_default "Storage capacity for NFS PV" "1Ti" "${current_storage_capacity}")
    wild-config-set "cloud.nfs.storageCapacity" "${storage_capacity}"
fi

# Docker Registry settings
current_registry_host=$(get_current_config "cloud.dockerRegistryHost")
if [ -z "$current_registry_host" ] || [ "$current_registry_host" = "null" ]; then
    registry_host=$(prompt_with_default "Docker registry hostname" "registry.${internal_domain}" "${current_registry_host}")
    wild-config-set "cloud.dockerRegistryHost" "${registry_host}"
fi

current_registry_storage=$(get_current_config "cluster.dockerRegistry.storage")
if [ -z "$current_registry_storage" ] || [ "$current_registry_storage" = "null" ]; then
    registry_storage=$(prompt_with_default "Docker registry storage size" "10Gi" "${current_registry_storage}")
    wild-config-set "cluster.dockerRegistry.storage" "${registry_storage}"
fi

print_success "Storage configuration completed"
echo ""

print_info "This phase prepares and installs core cluster services (MetalLB, Traefik, cert-manager, etc.)"
print_warning "Make sure your cluster is running and kubectl is configured!"

# Generate cluster services setup files
print_info "Generating cluster services setup files..."
wild-cluster-services-generate --force

if [ "${SKIP_INSTALL}" = false ]; then
    read -p "Do you want to install cluster services now? (y/N): " -r install_services
    
    if [[ $install_services =~ ^[Yy]$ ]]; then
        print_info "Installing cluster services..."
        wild-cluster-services-up
        SERVICES_INSTALLED=true
    else
        print_info "Skipping cluster services installation"
        print_info "You can install them later with: wild-cluster-services-up"
        SKIP_INSTALL=true
    fi
else
    print_info "Skipping cluster services installation (--skip-install specified)"
    print_info "You can install them later with: wild-cluster-services-up"
fi

if [ "${SKIP_INSTALL}" = false ] && [ "${SERVICES_INSTALLED:-false}" = true ]; then
    print_success "Phase 4 completed: Cluster services installation"
else
    print_success "Phase 4 completed: Cluster services configuration generated"
fi
echo ""

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

print_header "Wild-Cloud Services Setup Complete!"

print_success "Cluster services setup completed!"
echo ""

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

if [ -d "${WC_HOME}/setup/cluster" ]; then
    echo ""
    print_info "Generated service configurations:"
    echo "  - ${WC_HOME}/setup/cluster/"
fi

echo ""
if [ "${SKIP_INSTALL}" = false ] && [ "${SERVICES_INSTALLED:-false}" = true ]; then
    print_info "Cluster services have been installed!"
    echo ""
    
    if command -v kubectl >/dev/null 2>&1; then
        INTERNAL_DOMAIN=$(wild-config cloud.internalDomain 2>/dev/null || echo "your-internal-domain")
        echo "Next steps:"
        echo "  1. Access the dashboard at: https://dashboard.${INTERNAL_DOMAIN}"
        echo "  2. Get the dashboard token with: ./bin/dashboard-token"
        echo ""
        echo "To verify components, run:"
        echo "  - kubectl get pods -n cert-manager"
        echo "  - kubectl get pods -n externaldns"
        echo "  - kubectl get pods -n kubernetes-dashboard"
        echo "  - kubectl get clusterissuers"
    else
        echo "Next steps:"
        echo "  1. Verify your cluster services are running"
        echo "  2. Configure kubectl if not already done"
        echo "  3. Access your services via the configured ingress"
    fi
else
    echo "Next steps:"
    echo "  1. Ensure your cluster is running and kubectl is configured"
    echo "  2. Install services with: wild-cluster-services-up"
    echo "  3. Verify components are running correctly"
fi

print_success "Wild-Cloud setup completed!"