use anyhow::Result;
use tracing::info;

use crate::client::AdminClient;
use crate::output::{format_json, format_shard_detail, format_shards_table, OutputFormat};

/// List all shards
pub async fn list_shards(client: &AdminClient, format: OutputFormat) -> Result<()> {
    info!("Fetching shard list");
    let shards = client.all_ranges().await?;

    match format {
        OutputFormat::Table => {
            println!("\nSHARDS");
            println!("{}", format_shards_table(&shards));
        }
        OutputFormat::Json => {
            println!("{}", format_json(&shards)?);
        }
    }

    Ok(())
}

/// Show detailed information about a specific shard
pub async fn shard_info(client: &AdminClient, shard_id: u32, format: OutputFormat) -> Result<()> {
    info!("Fetching info for shard: {}", shard_id);
    let shard = client.shard_info(shard_id).await?;

    match format {
        OutputFormat::Table => {
            println!("{}", format_shard_detail(&shard));
        }
        OutputFormat::Json => {
            println!("{}", format_json(&shard)?);
        }
    }

    Ok(())
}

/// Show replica nodes for a specific shard
pub async fn shard_replicas(
    client: &AdminClient,
    shard_id: u32,
    format: OutputFormat,
) -> Result<()> {
    info!("Fetching replicas for shard: {}", shard_id);
    let shard = client.shard_info(shard_id).await?;

    match format {
        OutputFormat::Table => {
            println!("\nREPLICAS FOR SHARD {}", shard_id);
            println!("  Leader:    {}", shard.leader_node);
            println!("  Followers: {}", shard.replica_nodes.join(", "));
        }
        OutputFormat::Json => {
            let replicas = serde_json::json!({
                "shard_id": shard_id,
                "leader": shard.leader_node,
                "replicas": shard.replica_nodes,
            });
            println!("{}", format_json(&replicas)?);
        }
    }

    Ok(())
}
