#!/usr/bin/env herodo
// Pre-flight check: Ensure Kubernetes cluster is accessible
try {
    if !run("kubectl cluster-info").execute().success {
        print("SKIPPED: Kubernetes cluster is not accessible");
        exit(0);
    }
} catch(e) {
    print("SKIPPED: Kubernetes cluster is not accessible: " + e);
    exit(0);
}

//! Redis Cluster Deployment Example (Rhai)
//!
//! This script shows how to deploy a Redis cluster using Rhai scripting
//! with the KubernetesManager convenience methods.

print("=== Redis Cluster Deployment ===");

// Create Kubernetes manager for the rediscluster namespace
print("Creating Kubernetes manager for 'rediscluster' namespace...");
let km = kubernetes("rediscluster");
print("✓ Kubernetes manager created");

// Create the namespace if it doesn't exist
print("Creating namespace 'rediscluster' if it doesn't exist...");
create_namespace(km, "rediscluster");

// try {
//     create_namespace(km, "rediscluster");
//     print("✓ Namespace 'rediscluster' created");
// } catch(e) {
//     if e.to_string().contains("already exists") {
//         print("✓ Namespace 'rediscluster' already exists");
//     } else {
//         print("⚠️ Warning: " + e);
//     }
// }

// Clean up any existing resources first
print("\nCleaning up any existing Redis resources...");
try {
    delete_deployment(km, "rediscluster");
    print("✓ Deleted existing deployment");
} catch(e) {
    print("✓ No existing deployment to delete");
}

try {
    delete_service(km, "rediscluster");
    print("✓ Deleted existing service");
} catch(e) {
    print("✓ No existing service to delete");
}

// Create Redis cluster using the convenience method
print("\nDeploying Redis cluster...");

try {
    // Deploy Redis using the convenience method
    let result = deploy_application(km, "rediscluster", "redis:7-alpine", 3, 6379, #{
        "app": "rediscluster",
        "type": "rediscluster",
        "engine": "redis"
    }, #{
        "REDIS_PASSWORD": "redispassword",
        "REDIS_PORT": "6379",
        "REDIS_DATABASES": "16",
        "REDIS_MAXMEMORY": "256mb",
        "REDIS_MAXMEMORY_POLICY": "allkeys-lru"
    });
    print("✓ " + result);

    print("\n✅ Redis cluster deployed successfully!");

    print("\n📋 Connection Information:");
    print("  Host: rediscluster.rediscluster.svc.cluster.local");
    print("  Port: 6379");

    print("\n🔧 To connect from another pod:");
    print("  redis-cli -h rediscluster.rediscluster.svc.cluster.local");

    print("\n💡 Next steps:");
    print("  • Configure Redis authentication");
    print("  • Set up Redis clustering configuration");
    print("  • Add persistent storage");
    print("  • Configure memory policies");

} catch(e) {
    print("❌ Failed to deploy Redis cluster: " + e);
}

print("\n=== Deployment Complete ===");
