//! Rolling update and rollback example
//!
//! This example demonstrates rolling updates and rollbacks.
//!
//! Run with: cargo run --example rolling_update

use lmrc_kubernetes::config::{DeploymentOptions, RollbackOptions};
use lmrc_kubernetes::deployment::{ContainerSpec, DeploymentSpec};
use lmrc_kubernetes::{Client, ClientConfig};
use std::time::Duration;

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    // Initialize tracing
    tracing_subscriber::fmt::init();

    // Create client
    let config = ClientConfig::infer().await?;
    let client = Client::new(config, "default").await?;

    // Initial deployment - version 1.0
    println!("Deploying version 1.0...");
    let container_v1 = ContainerSpec::new("app", "myapp:v1.0")
        .with_port(8080)
        .with_env("VERSION", "1.0");

    let deployment = DeploymentSpec::new("rolling-app")
        .with_replicas(3)
        .with_container(container_v1);

    let options = DeploymentOptions::new().wait(true);
    client.deployments().apply(&deployment, &options).await?;

    println!("Version 1.0 deployed successfully");

    // Wait a bit
    tokio::time::sleep(Duration::from_secs(5)).await;

    // Rolling update to version 2.0
    println!("\nRolling update to version 2.0...");
    let container_v2 = ContainerSpec::new("app", "myapp:v2.0")
        .with_port(8080)
        .with_env("VERSION", "2.0");

    let deployment_v2 = DeploymentSpec::new("rolling-app")
        .with_replicas(3)
        .with_container(container_v2);

    client.deployments().apply(&deployment_v2, &options).await?;

    println!("Version 2.0 deployed successfully");

    // Get status
    let status = client.deployments().status("rolling-app").await?;
    println!(
        "Current status: {}/{} replicas ready",
        status.ready_replicas, status.replicas
    );

    // Demonstrate rollback
    println!("\nRolling back to previous version...");
    let rollback_opts = RollbackOptions::new().timeout_secs(180);
    client
        .deployments()
        .rollback("rolling-app", &rollback_opts)
        .await?;

    println!("Rolled back successfully to version 1.0");

    // Scale the deployment
    println!("\nScaling to 5 replicas...");
    client.deployments().scale("rolling-app", 5).await?;
    println!("Scaled successfully");

    Ok(())
}
