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

//! Kubernetes Deployment Example
//! Demonstrates creating and managing Kubernetes resources using a Deployment
//! All resource names are automatically normalized using name_fix_kubernetes
//! Deployment is used for long-running, self-healing workloads

let k = kubernetes();

print("=== Kubernetes State Before Reset ===");
print(k.md());

print("\n=== Resetting Kubernetes ===");
k.reset();
print(k.md());
print("Namespaces list: " + k.ns_list());

print("\n=== Deleting namespace: default-app ===");
k.ns_delete("default-app");

print("\n=== Creating namespace and resources in: default-app ===");
let ns = k.namespace("default-app");
ns.reset();

print("Pods list (after reset): " + ns.pods_list());
print(ns.md());

print("\n=== Creating ConfigMap: app-configmap ===");
ns.configmap("app-configmap")
    .set("app_secret", "value")
    .set("database_url", "postgres://localhost/mydb")
    .apply();

print("\n=== Creating Secret: app-secret ===");
ns.secret("app-secret")
    .set("username", "admin")
    .set("password", "secret123")
    .apply();

//looks like a pod but has multiple versions (the replicas)
print("\n=== Creating Deployment: app ===");
let deploy = ns.deployment("app")
    .replicas(1)

    .label("app", "default-app")
    .label("component", "web")

    .image("nginx:latest")
    .port(80)

    .env("ENV", "production")
    .env("LOG_LEVEL", "info")
    .env_from_configmap("app-configmap")
    .env_from_secret("app-secret")

    .memory(128, 512)        // MB: request / limit
    .cpu(1000, 2000)         // millicores: request / limit

    .readiness_http("/health", 80)
    .liveness_http("/health", 80)
        .initial_delay(10)
        .period(5)
        .failure_threshold(3)

    .apply();

print("Deployment 'app' created successfully");

print("\n=== Creating ClusterIP Service: web-service ===");
ns.service("web-service")
    .selector("app", "default-app")
    .expose(80).to_container(8080)
    .expose(443).to_container(8443)
    .apply();

print("\n=== Resource Summary ===");
print("Deployments: " + ns.deployments_list());
print("Services: " + ns.services_list());
print("Secrets: " + ns.secrets_list());
print("ConfigMaps: " + ns.configmaps_list());

print("\n✅ Kubernetes deployment example completed successfully!");
