#!/bin/bash

set -e
set -o pipefail

# Usage function
usage() {
    echo "Usage: wild-cluster-node-ip <node-name> [options]"
    echo ""
    echo "Get the current IP address of a cluster node by name."
    echo ""
    echo "Arguments:"
    echo "  node-name           Name of the node to get IP for"
    echo ""
    echo "Options:"
    echo "  --from-config       Get IP from local config.yaml"
    echo "  --from-talosctl     Get IP from Talos API"
    echo "                      Default: Query Kubernetes API (kubectl)"
    echo "  -h, --help          Show this help message"
    echo ""
    echo "Examples:"
    echo "  wild-cluster-node-ip control-1"
    echo "  wild-cluster-node-ip worker-1"
    echo "  wild-cluster-node-ip control-2 --from-config"
    echo "  wild-cluster-node-ip worker-2 --from-talosctl"
    echo ""
    echo "This script will:"
    echo "  - Query the specified source for the node's IP address"
    echo "  - Return only the internal IP address or exit with error if not found"
    echo ""
    echo "Requirements:"
    echo "  - Must be run from a Wild Cloud directory"
    echo "  - kubectl and/or talosctl must be configured for cluster access"
}

# Parse arguments
NODE_NAME=""
SOURCE="kubectl"

while [[ $# -gt 0 ]]; do
    case $1 in
        --from-config)
            SOURCE="config"
            shift
            ;;
        --from-talosctl)
            SOURCE="talosctl"
            shift
            ;;
        -h|--help)
            usage
            exit 0
            ;;
        -*)
            echo "Unknown option $1"
            usage
            exit 1
            ;;
        *)
            if [ -z "$NODE_NAME" ]; then
                NODE_NAME="$1"
            else
                echo "Unexpected argument: $1"
                usage
                exit 1
            fi
            shift
            ;;
    esac
done

# Check if node name was provided
if [ -z "$NODE_NAME" ]; then
    echo "Error: Node name is required"
    usage
    exit 1
fi

# Initialize Wild Cloud environment
if [ -z "${WC_ROOT}" ]; then
    echo "Error: WC_ROOT is not set" >&2
    exit 1
else
    source "${WC_ROOT}/scripts/common.sh"
    init_wild_env
fi

# Function to get IP from config.yaml
get_ip_from_config() {
    local node_name="$1"
    local ip
    
    ip=$(yq eval ".cluster.nodes.active.\"${node_name}\".currentIp" "${WC_HOME}/config.yaml" 2>/dev/null || echo "")
    
    if [ -n "$ip" ] && [ "$ip" != "null" ]; then
        echo "$ip"
        return 0
    else
        return 1
    fi
}

# Function to get IP from kubectl
get_ip_from_kubectl() {
    local node_name="$1"
    local ip
    
    # Check if kubectl is available and configured
    if ! command -v kubectl >/dev/null 2>&1; then
        return 1
    fi
    
    # Try to get node info from kubectl
    if ! kubectl get nodes "$node_name" >/dev/null 2>&1; then
        return 1
    fi
    
    # Get internal IP address
    ip=$(kubectl get node "$node_name" -o jsonpath='{.status.addresses[?(@.type=="InternalIP")].address}' 2>/dev/null || echo "")
    
    if [ -n "$ip" ]; then
        echo "$ip"
        return 0
    else
        return 1
    fi
}

# Function to get IP from talosctl
get_ip_from_talosctl() {
    local node_name="$1"
    local ip
    
    # Check if talosctl is available and configured
    if ! command -v talosctl >/dev/null 2>&1; then
        return 1
    fi
    
    # Try to get node info from talosctl
    if talosctl get members >/dev/null 2>&1; then
        # Find the specific node and get its first IP address
        ip=$(talosctl get members -o json 2>/dev/null | jq -r --arg hostname "$node_name" 'select(.spec.hostname == $hostname) | .spec.addresses[0]' 2>/dev/null | grep -v "null" | head -n1 || echo "")
        
        if [ -n "$ip" ]; then
            echo "$ip"
            return 0
        fi
    fi
    
    return 1
}


# Main logic
case $SOURCE in
    config)
        if ip=$(get_ip_from_config "$NODE_NAME"); then
            echo "$ip"
        else
            echo "Error: Node $NODE_NAME not found in config.yaml or no currentIp set" >&2
            exit 1
        fi
        ;;
    kubectl)
        if ip=$(get_ip_from_kubectl "$NODE_NAME"); then
            echo "$ip"
        else
            echo "Error: Could not get IP for node $NODE_NAME via kubectl" >&2
            exit 1
        fi
        ;;
    talosctl)
        if ip=$(get_ip_from_talosctl "$NODE_NAME"); then
            echo "$ip"
        else
            echo "Error: Could not get IP for node $NODE_NAME via talosctl" >&2
            exit 1
        fi
        ;;
esac