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

# Phase tracking variables
SKIP_SCAFFOLD=false
SKIP_CLUSTER=false
SKIP_SERVICES=false

# Parse arguments
while [[ $# -gt 0 ]]; do
    case $1 in
        --skip-scaffold)
            SKIP_SCAFFOLD=true
            shift
            ;;
        --skip-cluster)
            SKIP_CLUSTER=true
            shift
            ;;
        --skip-services)
            SKIP_SERVICES=true
            shift
            ;;
        -h|--help)
            echo "Usage: $0 [component-options]"
            echo ""
            echo "Complete Wild-Cloud setup - runs all components in sequence."
            echo ""
            echo "Component Control Options:"
            echo "  --skip-scaffold     Skip scaffold setup (cloud initialization)"
            echo "  --skip-cluster      Skip cluster setup (Phases 1-3)"
            echo "  --skip-services     Skip services setup (Phase 4)"
            echo "  -h, --help          Show this help message"
            echo ""
            echo "This script runs:"
            echo "  1. wild-setup-scaffold   # Cloud initialization and basic config"
            echo "  2. wild-setup-cluster    # Cluster infrastructure (Phases 1-3)"
            echo "  3. wild-setup-services   # Cluster services (Phase 4)"
            echo ""
            echo "You can also run these components individually:"
            echo "  - wild-setup-scaffold  [--update]"
            echo "  - wild-setup-cluster   [--skip-installer] [--skip-hardware] [--skip-configs]"
            echo "  - wild-setup-services  [--skip-install]"
            echo ""
            echo "For detailed options for each component, use:"
            echo "  wild-setup-scaffold --help"
            echo "  wild-setup-cluster --help"
            echo "  wild-setup-services --help"
            exit 0
            ;;
        -*)
            echo "Unknown option $1"
            echo "Usage: $0 [component-options]"
            echo "Use --help for full usage information"
            exit 1
            ;;
        *)
            echo "Unexpected argument: $1"
            echo "Usage: $0 [component-options]"
            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

print_header "Wild-Cloud Complete Setup"
print_info "Running complete Wild-Cloud setup using modular components"
echo ""

# =============================================================================
# COMPONENT 1: SCAFFOLD SETUP
# =============================================================================

if [ "${SKIP_SCAFFOLD}" = false ]; then
    print_header "Component 1: Scaffold Setup"
    print_info "Running wild-setup-scaffold..."
    
    if wild-setup-scaffold; then
        print_success "Component 1 completed: Scaffold setup"
    else
        print_error "Component 1 failed: Scaffold setup"
        exit 1
    fi
    echo ""
else
    print_info "Skipping Component 1: Scaffold Setup"
fi

# =============================================================================
# COMPONENT 2: CLUSTER SETUP
# =============================================================================

if [ "${SKIP_CLUSTER}" = false ]; then
    print_header "Component 2: Cluster Setup"
    print_info "Running wild-setup-cluster..."
    
    if wild-setup-cluster; then
        print_success "Component 2 completed: Cluster setup"
    else
        print_error "Component 2 failed: Cluster setup"
        exit 1
    fi
    echo ""
else
    print_info "Skipping Component 2: Cluster Setup"
fi

# =============================================================================
# COMPONENT 3: SERVICES SETUP
# =============================================================================

if [ "${SKIP_SERVICES}" = false ]; then
    print_header "Component 3: Services Setup"
    print_info "Running wild-setup-services..."
    
    if wild-setup-services; then
        print_success "Component 3 completed: Services setup"
    else
        print_error "Component 3 failed: Services setup"
        exit 1
    fi
    echo ""
else
    print_info "Skipping Component 3: Services Setup"
fi

# =============================================================================
# FINAL SUMMARY
# =============================================================================

print_header "Wild-Cloud Complete Setup Finished!"

print_success "All components completed successfully!"
echo ""

print_info "What was accomplished:"
if [ "${SKIP_SCAFFOLD}" = false ]; then
    print_info "✅ Component 1: Scaffold setup (cloud initialization)"
else
    print_info "⏸️  Component 1: Scaffold setup (skipped)"
fi

if [ "${SKIP_CLUSTER}" = false ]; then
    print_info "✅ Component 2: Cluster setup (Phases 1-3)"
else
    print_info "⏸️  Component 2: Cluster setup (skipped)"
fi

if [ "${SKIP_SERVICES}" = false ]; then
    print_info "✅ Component 3: Services setup (Phase 4)"
else
    print_info "⏸️  Component 3: Services setup (skipped)"
fi

echo ""
print_info "Individual components can be run separately:"
echo "  - wild-setup-scaffold  # Cloud initialization"
echo "  - wild-setup-cluster   # Cluster infrastructure" 
echo "  - wild-setup-services  # Cluster services"

echo ""
if [ "${SKIP_SERVICES}" = false ] && command -v kubectl >/dev/null 2>&1; then
    if [ -f "${WC_HOME}/config.yaml" ]; then
        INTERNAL_DOMAIN=$(wild-config cloud.internalDomain 2>/dev/null || echo "your-internal-domain")
        print_info "Your Wild-Cloud is ready!"
        echo "  Dashboard: https://dashboard.${INTERNAL_DOMAIN}"
        echo "  Get token: ./bin/dashboard-token"
    fi
else
    print_info "Complete the remaining setup steps to finalize your Wild-Cloud deployment"
fi

print_success "Wild-Cloud setup completed!"