#!/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 Advanced Networking
//! Multi-tier application setup with services and pods

let k = kubernetes();

print("=== Multi-Tier Application ===");

// Frontend tier
let frontend = k.namespace("frontend");
frontend.pod("nginx")
    .image("nginx:latest")
    .port(80)
    .label("app", "web")
    .apply();

frontend.service("web-service")
    .selector("app", "web")
    .expose(80)
    // .nodeport()                    // Optional: expose externally
    // .via_node(30080)               // Optional: node port number
    .apply();

print("✅ Frontend tier created");

// Backend tier
let backend = k.namespace("backend");
backend.pod("api")
    .image("node:18-alpine")
    .port(8080)
    .label("app", "api")
    .env("NODE_ENV", "production")
    // .memory(256, 1024)             // Optional: memory limits
    // .cpu(500, 2000)                // Optional: CPU limits
    .apply();

backend.service("api-service")
    .selector("app", "api")
    .expose(8080)
    .to_container(8080)
    .apply();

print("✅ Backend tier created");

// Database tier
let database = k.namespace("database");
database.pod("postgres")
    .image("postgres:15-alpine")
    .port(5432)
    .label("app", "db")
    .env("POSTGRES_USER", "admin")
    .apply();

database.service("db-service")
    .selector("app", "db")
    .expose(5432)
    .apply();

print("✅ Database tier created");

// Microservices mesh
let mesh = k.namespace("microservices");
let services = [
    #{ name: "users", port: 8001 },
    #{ name: "orders", port: 8002 },
    #{ name: "payments", port: 8003 }
];

for svc in services {
    mesh.pod(svc.name + "-pod")
        .image("node:18-alpine")
        .port(svc.port)
        .label("app", svc.name)
        .apply();

    mesh.service(svc.name)
        .selector("app", svc.name)
        .expose(svc.port)
        .apply();
}

print("✅ Microservices mesh created");
print("Done!");
