#!/usr/bin/env zsh

# Function to display usage information
usage() {
    echo "Usage: source $0 <environment> [version]"
    echo "  environment: The environment to use (dev, test, bugfix, integration, prod)"
    echo "  version    : (Optional) Specific release version to deploy"
    echo "               If not specified, uses 'latest' (except for dev environment)"
}

# Check if the script is sourced - improved for both bash and zsh
is_sourced() {
    if [[ -n "$ZSH_VERSION" ]]; then
        # In zsh, check if we're in a sourced context
        [[ "$ZSH_EVAL_CONTEXT" =~ "(:file|:cmdsubst)" ]] || [[ "$0" != "$ZSH_ARGZERO" ]]
    else
        # In bash, compare BASH_SOURCE with $0
        [[ "${BASH_SOURCE[0]}" != "${0}" ]]
    fi
}

if ! is_sourced; then
    echo "Error: This script must be sourced, not executed directly."
    echo "Please run: source $0 <environment> [version]"
    if [[ -n "$ZSH_VERSION" ]]; then
        return 1 2>/dev/null || exit 1
    else
        exit 1
    fi
fi

# Check if an environment is provided
if [ $# -eq 0 ]; then
    usage
    return 1
fi

ENVIRONMENT=$1
VERSION=${2:-latest}  # Default to latest if not specified

# Check if required tools are available
if ! command -v kubectl &> /dev/null; then
    echo "Error: kubectl is not installed or not in PATH"
    echo "Please install kubectl first"
    return 1
fi

if ! command -v kind &> /dev/null; then
    echo "Error: kind is not installed or not in PATH"
    echo "Please install kind first"
    return 1
fi

echo "Using kubectl: $(command -v kubectl)"
echo "Using kind: $(command -v kind)"

# Set variables based on the environment
case $ENVIRONMENT in
    dev)
        K8S_CLUSTER="kind-eveai-dev-cluster"
        K8S_NAMESPACE="eveai-dev"
        K8S_CONFIG_DIR="$PWD/k8s/dev"
        VERSION="latest"  # Always use latest for dev
        ;;
    test)
        K8S_CLUSTER="kind-eveai-test-cluster"
        K8S_NAMESPACE="eveai-test"
        K8S_CONFIG_DIR="$PWD/k8s/test"
        ;;
    bugfix)
        K8S_CLUSTER="kind-eveai-bugfix-cluster"
        K8S_NAMESPACE="eveai-bugfix"
        K8S_CONFIG_DIR="$PWD/k8s/bugfix"
        ;;
    integration)
        K8S_CLUSTER="kind-eveai-integration-cluster"
        K8S_NAMESPACE="eveai-integration"
        K8S_CONFIG_DIR="$PWD/k8s/integration"
        ;;
    prod)
        K8S_CLUSTER="kind-eveai-prod-cluster"
        K8S_NAMESPACE="eveai-prod"
        K8S_CONFIG_DIR="$PWD/k8s/prod"
        ;;
    *)
        echo "Invalid environment: $ENVIRONMENT"
        usage
        return 1
        ;;
esac

# Set up logging directories
LOG_DIR="$HOME/k8s-logs/$ENVIRONMENT"
mkdir -p "$LOG_DIR"

# Check if config directory exists
if [[ ! -d "$K8S_CONFIG_DIR" ]]; then
    echo "Warning: Config directory '$K8S_CONFIG_DIR' does not exist."
    if [[ "$ENVIRONMENT" != "dev" && -d "$PWD/k8s/dev" ]]; then
        echo -n "Do you want to create it based on dev environment? (y/n): "
        read -r CREATE_DIR
        if [[ "$CREATE_DIR" == "y" || "$CREATE_DIR" == "Y" ]]; then
            mkdir -p "$K8S_CONFIG_DIR"
            cp -r "$PWD/k8s/dev/"* "$K8S_CONFIG_DIR/"
            echo "Created $K8S_CONFIG_DIR with dev environment templates."
            echo "Please review and modify the configurations for $ENVIRONMENT environment."
        else
            echo "Cannot proceed without a valid config directory."
            return 1
        fi
    else
        echo "Cannot create $K8S_CONFIG_DIR: dev environment not found."
        return 1
    fi
fi

# Set cluster context
echo "Setting kubectl context to $K8S_CLUSTER..."
if kubectl config use-context "$K8S_CLUSTER" &>/dev/null; then
    echo "✅ Using cluster context: $K8S_CLUSTER"
else
    echo "⚠️  Warning: Failed to switch to context $K8S_CLUSTER"
    echo "   Make sure the cluster is running: kind get clusters"
fi

# Set environment variables
export K8S_ENVIRONMENT=$ENVIRONMENT
export K8S_VERSION=$VERSION
export K8S_CLUSTER=$K8S_CLUSTER
export K8S_NAMESPACE=$K8S_NAMESPACE
export K8S_CONFIG_DIR=$K8S_CONFIG_DIR
export K8S_LOG_DIR=$LOG_DIR

echo "Set K8S_ENVIRONMENT to $ENVIRONMENT"
echo "Set K8S_VERSION to $VERSION"
echo "Set K8S_CLUSTER to $K8S_CLUSTER"
echo "Set K8S_NAMESPACE to $K8S_NAMESPACE"
echo "Set K8S_CONFIG_DIR to $K8S_CONFIG_DIR"
echo "Set K8S_LOG_DIR to $LOG_DIR"

# Source supporting scripts
SCRIPT_DIR="$(dirname "${BASH_SOURCE[0]:-$0}")"
if [[ -f "$SCRIPT_DIR/scripts/k8s-functions.sh" ]]; then
    source "$SCRIPT_DIR/scripts/k8s-functions.sh"
else
    echo "Warning: k8s-functions.sh not found, some functions may not work"
fi

if [[ -f "$SCRIPT_DIR/scripts/service-groups.sh" ]]; then
    source "$SCRIPT_DIR/scripts/service-groups.sh"
else
    echo "Warning: service-groups.sh not found, service groups may not be defined"
fi

if [[ -f "$SCRIPT_DIR/scripts/dependency-checks.sh" ]]; then
    source "$SCRIPT_DIR/scripts/dependency-checks.sh"
else
    echo "Warning: dependency-checks.sh not found, dependency checking disabled"
fi

if [[ -f "$SCRIPT_DIR/scripts/logging-utils.sh" ]]; then
    source "$SCRIPT_DIR/scripts/logging-utils.sh"
else
    echo "Warning: logging-utils.sh not found, logging may be limited"
fi

# Core service management functions (similar to pc* functions)
kup() {
    local group=${1:-all}
    log_operation "INFO" "Starting service group: $group"
    deploy_service_group "$group"
}

kdown() {
    local group=${1:-all}
    log_operation "INFO" "Stopping service group: $group (keeping data)"
    stop_service_group "$group" --keep-data
}

kstop() {
    local group=${1:-all}
    log_operation "INFO" "Stopping service group: $group (without removal)"
    stop_service_group "$group" --stop-only
}

kstart() {
    local group=${1:-all}
    log_operation "INFO" "Starting stopped service group: $group"
    start_service_group "$group"
}

kps() {
    echo "🔍 Service Status Overview for $K8S_ENVIRONMENT:"
    echo "=================================================="
    kubectl get pods,services,ingress -n "$K8S_NAMESPACE" 2>/dev/null || echo "Namespace $K8S_NAMESPACE not found or no resources"
}

klogs() {
    local service=$1
    if [[ -z "$service" ]]; then
        echo "Available services in $K8S_ENVIRONMENT:"
        kubectl get deployments -n "$K8S_NAMESPACE" --no-headers 2>/dev/null | awk '{print "  " $1}' || echo "  No deployments found"
        return 1
    fi
    log_operation "INFO" "Viewing logs for service: $service"
    kubectl logs -f deployment/$service -n "$K8S_NAMESPACE"
}

krefresh() {
    local group=${1:-all}
    log_operation "INFO" "Refreshing service group: $group"
    stop_service_group "$group" --stop-only
    sleep 5
    deploy_service_group "$group"
}

# Structured deployment of all services (like deploy-all-services.sh)
kup-all-structured() {
    log_operation "INFO" "Starting structured deployment of all services"
    deploy_all_structured
}

# Test connectivity to all services
ktest() {
    log_operation "INFO" "Testing service connectivity"
    test_connectivity_ingress
}

# Show connection information
kinfo() {
    log_operation "INFO" "Showing connection information"
    show_connection_info
}

# Individual service management functions for apps group
kup-app() {
    log_operation "INFO" "Starting eveai-app"
    check_infrastructure_ready
    deploy_individual_service "eveai-app" "apps"
}

kdown-app() {
    log_operation "INFO" "Stopping eveai-app"
    stop_individual_service "eveai-app" --keep-data
}

kstop-app() {
    log_operation "INFO" "Stopping eveai-app (without removal)"
    stop_individual_service "eveai-app" --stop-only
}

kstart-app() {
    log_operation "INFO" "Starting stopped eveai-app"
    start_individual_service "eveai-app"
}

kup-api() {
    log_operation "INFO" "Starting eveai-api"
    check_infrastructure_ready
    deploy_individual_service "eveai-api" "apps"
}

kdown-api() {
    log_operation "INFO" "Stopping eveai-api"
    stop_individual_service "eveai-api" --keep-data
}

kstop-api() {
    log_operation "INFO" "Stopping eveai-api (without removal)"
    stop_individual_service "eveai-api" --stop-only
}

kstart-api() {
    log_operation "INFO" "Starting stopped eveai-api"
    start_individual_service "eveai-api"
}

kup-chat-client() {
    log_operation "INFO" "Starting eveai-chat-client"
    check_infrastructure_ready
    deploy_individual_service "eveai-chat-client" "apps"
}

kdown-chat-client() {
    log_operation "INFO" "Stopping eveai-chat-client"
    stop_individual_service "eveai-chat-client" --keep-data
}

kstop-chat-client() {
    log_operation "INFO" "Stopping eveai-chat-client (without removal)"
    stop_individual_service "eveai-chat-client" --stop-only
}

kstart-chat-client() {
    log_operation "INFO" "Starting stopped eveai-chat-client"
    start_individual_service "eveai-chat-client"
}

kup-workers() {
    log_operation "INFO" "Starting eveai-workers"
    check_app_dependencies "eveai-workers"
    deploy_individual_service "eveai-workers" "apps"
}

kdown-workers() {
    log_operation "INFO" "Stopping eveai-workers"
    stop_individual_service "eveai-workers" --keep-data
}

kstop-workers() {
    log_operation "INFO" "Stopping eveai-workers (without removal)"
    stop_individual_service "eveai-workers" --stop-only
}

kstart-workers() {
    log_operation "INFO" "Starting stopped eveai-workers"
    start_individual_service "eveai-workers"
}

kup-chat-workers() {
    log_operation "INFO" "Starting eveai-chat-workers"
    check_app_dependencies "eveai-chat-workers"
    deploy_individual_service "eveai-chat-workers" "apps"
}

kdown-chat-workers() {
    log_operation "INFO" "Stopping eveai-chat-workers"
    stop_individual_service "eveai-chat-workers" --keep-data
}

kstop-chat-workers() {
    log_operation "INFO" "Stopping eveai-chat-workers (without removal)"
    stop_individual_service "eveai-chat-workers" --stop-only
}

kstart-chat-workers() {
    log_operation "INFO" "Starting stopped eveai-chat-workers"
    start_individual_service "eveai-chat-workers"
}

kup-beat() {
    log_operation "INFO" "Starting eveai-beat"
    check_app_dependencies "eveai-beat"
    deploy_individual_service "eveai-beat" "apps"
}

kdown-beat() {
    log_operation "INFO" "Stopping eveai-beat"
    stop_individual_service "eveai-beat" --keep-data
}

kstop-beat() {
    log_operation "INFO" "Stopping eveai-beat (without removal)"
    stop_individual_service "eveai-beat" --stop-only
}

kstart-beat() {
    log_operation "INFO" "Starting stopped eveai-beat"
    start_individual_service "eveai-beat"
}

kup-entitlements() {
    log_operation "INFO" "Starting eveai-entitlements"
    check_infrastructure_ready
    deploy_individual_service "eveai-entitlements" "apps"
}

kdown-entitlements() {
    log_operation "INFO" "Stopping eveai-entitlements"
    stop_individual_service "eveai-entitlements" --keep-data
}

kstop-entitlements() {
    log_operation "INFO" "Stopping eveai-entitlements (without removal)"
    stop_individual_service "eveai-entitlements" --stop-only
}

kstart-entitlements() {
    log_operation "INFO" "Starting stopped eveai-entitlements"
    start_individual_service "eveai-entitlements"
}

# Static files management functions
kdeploy-static() {
    local dry_run=""
    if [[ "$1" == "--dry-run" ]]; then
        dry_run="--dry-run"
    fi
    
    echo "🚀 Deploying static files to $K8S_ENVIRONMENT environment..."
    "$K8S_CONFIG_DIR/../deploy-static-files.sh" "$K8S_ENVIRONMENT" "$dry_run"
}

kstatic-status() {
    echo "📊 Static Files Status for $K8S_ENVIRONMENT:"
    echo "============================================="
    kubectl get pvc static-files-pvc -n "$K8S_NAMESPACE" 2>/dev/null || echo "PVC not found"
    kubectl get pods -l app=static-files -n "$K8S_NAMESPACE" 2>/dev/null || echo "No static-files pods found"
    echo ""
    echo "💾 PVC Usage:"
    kubectl describe pvc static-files-pvc -n "$K8S_NAMESPACE" 2>/dev/null | grep -E "(Capacity|Used)" || echo "Usage info not available"
}

# Cluster management functions
cluster-start() {
    log_operation "INFO" "Starting cluster: $K8S_CLUSTER"
    if kind get clusters | grep -q "${K8S_CLUSTER#kind-}"; then
        echo "✅ Cluster $K8S_CLUSTER is already running"
    else
        echo "❌ Cluster $K8S_CLUSTER is not running"
        echo "Use setup script to create cluster: $K8S_CONFIG_DIR/setup-${ENVIRONMENT}-cluster.sh"
    fi
}

cluster-stop() {
    log_operation "INFO" "Stopping cluster: $K8S_CLUSTER"
    echo "⚠️  Note: Kind clusters cannot be stopped, only deleted"
    echo "Use 'cluster-delete' to remove the cluster completely"
}

cluster-delete() {
    log_operation "INFO" "Deleting cluster: $K8S_CLUSTER"
    echo -n "Are you sure you want to delete cluster $K8S_CLUSTER? (y/n): "
    read -r CONFIRM
    if [[ "$CONFIRM" == "y" || "$CONFIRM" == "Y" ]]; then
        kind delete cluster --name "${K8S_CLUSTER#kind-}"
        echo "✅ Cluster $K8S_CLUSTER deleted"
    else
        echo "❌ Cluster deletion cancelled"
    fi
}

cluster-status() {
    echo "🔍 Cluster Status for $K8S_ENVIRONMENT:"
    echo "======================================"
    echo "Cluster: $K8S_CLUSTER"
    echo "Namespace: $K8S_NAMESPACE"
    echo ""
    
    if kind get clusters | grep -q "${K8S_CLUSTER#kind-}"; then
        echo "✅ Cluster is running"
        echo ""
        echo "Nodes:"
        kubectl get nodes 2>/dev/null || echo "  Unable to get nodes"
        echo ""
        echo "Namespaces:"
        kubectl get namespaces 2>/dev/null || echo "  Unable to get namespaces"
    else
        echo "❌ Cluster is not running"
    fi
}

# Export functions - handle both bash and zsh
if [[ -n "$ZSH_VERSION" ]]; then
    # In zsh, functions are automatically available in subshells
    # But we can make them available globally with typeset
    typeset -f kup kdown kstop kstart kps klogs krefresh > /dev/null
    typeset -f kup-all-structured ktest kinfo > /dev/null
    typeset -f kup-app kdown-app kstop-app kstart-app > /dev/null
    typeset -f kup-api kdown-api kstop-api kstart-api > /dev/null
    typeset -f kup-chat-client kdown-chat-client kstop-chat-client kstart-chat-client > /dev/null
    typeset -f kup-workers kdown-workers kstop-workers kstart-workers > /dev/null
    typeset -f kup-chat-workers kdown-chat-workers kstop-chat-workers kstart-chat-workers > /dev/null
    typeset -f kup-beat kdown-beat kstop-beat kstart-beat > /dev/null
    typeset -f kup-entitlements kdown-entitlements kstop-entitlements kstart-entitlements > /dev/null
    typeset -f cluster-start cluster-stop cluster-delete cluster-status > /dev/null
else
    # Bash style export
    export -f kup kdown kstop kstart kps klogs krefresh
    export -f kup-all-structured ktest kinfo
    export -f kup-app kdown-app kstop-app kstart-app
    export -f kup-api kdown-api kstop-api kstart-api
    export -f kup-chat-client kdown-chat-client kstop-chat-client kstart-chat-client
    export -f kup-workers kdown-workers kstop-workers kstart-workers
    export -f kup-chat-workers kdown-chat-workers kstop-chat-workers kstart-chat-workers
    export -f kup-beat kdown-beat kstop-beat kstart-beat
    export -f kup-entitlements kdown-entitlements kstop-entitlements kstart-entitlements
    export -f cluster-start cluster-stop cluster-delete cluster-status
fi

echo "✅ Kubernetes environment switched to $ENVIRONMENT with version $VERSION"
echo "🏗️  Cluster: $K8S_CLUSTER"
echo "📁 Config Dir: $K8S_CONFIG_DIR"
echo "📝 Log Dir: $LOG_DIR"
echo ""
echo "Available commands:"
echo "  Service Groups:"
echo "    kup [group]       - start service group (infrastructure|apps|static|monitoring|all)"
echo "    kdown [group]     - stop service group, keep data"
echo "    kstop [group]     - stop service group without removal"
echo "    kstart [group]    - start stopped service group"
echo "    krefresh [group]  - restart service group"
echo ""
echo "  Structured Deployment:"
echo "    kup-all-structured - deploy all services in structured order (like deploy-all-services.sh)"
echo ""
echo "  Individual App Services:"
echo "    kup-app           - start eveai-app"
echo "    kup-api           - start eveai-api"
echo "    kup-chat-client   - start eveai-chat-client"
echo "    kup-workers       - start eveai-workers"
echo "    kup-chat-workers  - start eveai-chat-workers"
echo "    kup-beat          - start eveai-beat"
echo "    kup-entitlements  - start eveai-entitlements"
echo "    (and corresponding kdown-, kstop-, kstart- functions)"
echo ""
echo "  Status & Testing:"
echo "    kps               - show service status"
echo "    klogs [service]   - view service logs"
echo "    ktest             - test service connectivity"
echo "    kinfo             - show connection information"
echo ""
echo "  Cluster Management:"
echo "    cluster-start     - start cluster"
echo "    cluster-stop      - stop cluster"
echo "    cluster-delete    - delete cluster"
echo "    cluster-status    - show cluster status"