#!/usr/bin/env herodo
//! Multi-namespace Kubernetes operations example
//!
//! This script demonstrates working with multiple namespaces and comparing resources across them.
//! 
//! Prerequisites:
//! - A running Kubernetes cluster
//! - Valid kubeconfig file or in-cluster configuration
//! - Appropriate permissions for the operations
//!
//! Usage:
//!   herodo examples/kubernetes/multi_namespace_operations.rhai

print("=== SAL Kubernetes Multi-Namespace Operations Example ===");

// Define namespaces to work with
let target_namespaces = ["default", "kube-system"];
let managers = #{};

print("Creating managers for multiple namespaces...");

// Create managers for each namespace
for ns in target_namespaces {
    try {
        let km = kubernetes_manager_new(ns);
        managers[ns] = km;
        print("✓ Created manager for namespace: " + ns);
    } catch(e) {
        print("✗ Failed to create manager for " + ns + ": " + e);
    }
}

// Function to safely get resource counts
fn get_safe_counts(km) {
    try {
        return resource_counts(km);
    } catch(e) {
        print("  Warning: Could not get resource counts - " + e);
        return #{};
    }
}

// Function to safely get pod list
fn get_safe_pods(km) {
    try {
        return pods_list(km);
    } catch(e) {
        print("  Warning: Could not list pods - " + e);
        return [];
    }
}

// Compare resource counts across namespaces
print("\n--- Resource Comparison Across Namespaces ---");
let total_resources = #{};

for ns in target_namespaces {
    if ns in managers {
        let km = managers[ns];
        print("\nNamespace: " + ns);
        let counts = get_safe_counts(km);
        
        for resource_type in counts.keys() {
            let count = counts[resource_type];
            print("  " + resource_type + ": " + count);
            
            // Accumulate totals
            if resource_type in total_resources {
                total_resources[resource_type] = total_resources[resource_type] + count;
            } else {
                total_resources[resource_type] = count;
            }
        }
    }
}

print("\n--- Total Resources Across All Namespaces ---");
for resource_type in total_resources.keys() {
    print("Total " + resource_type + ": " + total_resources[resource_type]);
}

// Find namespaces with the most resources
print("\n--- Namespace Resource Analysis ---");
let namespace_totals = #{};

for ns in target_namespaces {
    if ns in managers {
        let km = managers[ns];
        let counts = get_safe_counts(km);
        let total = 0;
        
        for resource_type in counts.keys() {
            total = total + counts[resource_type];
        }
        
        namespace_totals[ns] = total;
        print("Namespace '" + ns + "' has " + total + " total resources");
    }
}

// Find the busiest namespace
let busiest_ns = "";
let max_resources = 0;
for ns in namespace_totals.keys() {
    if namespace_totals[ns] > max_resources {
        max_resources = namespace_totals[ns];
        busiest_ns = ns;
    }
}

if busiest_ns != "" {
    print("🏆 Busiest namespace: '" + busiest_ns + "' with " + max_resources + " resources");
}

// Detailed pod analysis
print("\n--- Pod Analysis Across Namespaces ---");
let all_pods = [];

for ns in target_namespaces {
    if ns in managers {
        let km = managers[ns];
        let pods = get_safe_pods(km);
        
        print("\nNamespace '" + ns + "' pods:");
        if pods.len() == 0 {
            print("  (no pods)");
        } else {
            for pod in pods {
                print("  - " + pod);
                all_pods.push(ns + "/" + pod);
            }
        }
    }
}

print("\n--- All Pods Summary ---");
print("Total pods across all namespaces: " + all_pods.len());

// Look for common pod name patterns
print("\n--- Pod Name Pattern Analysis ---");
let patterns = #{
    "system": 0,
    "kube": 0,
    "coredns": 0,
    "proxy": 0,
    "controller": 0
};

for pod_full_name in all_pods {
    let pod_name = pod_full_name.to_lower();
    
    for pattern in patterns.keys() {
        if pod_name.contains(pattern) {
            patterns[pattern] = patterns[pattern] + 1;
        }
    }
}

print("Common pod name patterns found:");
for pattern in patterns.keys() {
    if patterns[pattern] > 0 {
        print("  '" + pattern + "': " + patterns[pattern] + " pods");
    }
}

// Namespace health check
print("\n--- Namespace Health Check ---");
for ns in target_namespaces {
    if ns in managers {
        let km = managers[ns];
        print("\nChecking namespace: " + ns);
        
        // Check if namespace exists (should always be true for our managers)
        let exists = namespace_exists(km, ns);
        if exists {
            print("  ✓ Namespace exists and is accessible");
        } else {
            print("  ✗ Namespace existence check failed");
        }
        
        // Try to get resource counts as a health indicator
        let counts = get_safe_counts(km);
        if counts.len() > 0 {
            print("  ✓ Can access resources (" + counts.len() + " resource types)");
        } else {
            print("  ⚠ No resources found or access limited");
        }
    }
}

// Create a summary report
print("\n--- Summary Report ---");
print("Namespaces analyzed: " + target_namespaces.len());
print("Total unique resource types: " + total_resources.len());

let grand_total = 0;
for resource_type in total_resources.keys() {
    grand_total = grand_total + total_resources[resource_type];
}
print("Grand total resources: " + grand_total);

print("\nResource breakdown:");
for resource_type in total_resources.keys() {
    let count = total_resources[resource_type];
    let percentage = (count * 100) / grand_total;
    print("  " + resource_type + ": " + count + " (" + percentage + "%)");
}

print("\n=== Multi-namespace operations example completed! ===");
