//! `ph today`: Fetch and display today's top launches.

use ph_cli_core::{Client, Result};

/// Execute the today command.
pub async fn execute(client: &mut Client, limit: Option<usize>, as_json: bool) -> Result<()> {
    let posts = client.today(limit).await?;

    if posts.is_empty() {
        if as_json {
            println!("[]");
        } else {
            println!("No launches found for today.");
        }
        return Ok(());
    }

    if as_json {
        let json = serde_json::to_string_pretty(&posts)?;
        println!("{}", json);
    } else {
        print_table(&posts);
    }

    Ok(())
}

/// Pretty-print posts as a formatted table.
fn print_table(posts: &[ph_cli_core::Post]) {
    // Find column widths
    let max_name_len = posts
        .iter()
        .map(|p| p.name.len())
        .max()
        .unwrap_or(0)
        .min(30);
    let max_tagline_len = posts
        .iter()
        .map(|p| p.tagline.len())
        .max()
        .unwrap_or(0)
        .min(50);

    // Header
    let header = format!(
        "  {:<4} {:<width_name$} {:<width_tagline$} {:>6} {:>8}",
        "#",
        "Name",
        "Tagline",
        "Votes",
        "Comments",
        width_name = max_name_len,
        width_tagline = max_tagline_len,
    );

    println!("\n{}", header);
    println!("{}", "─".repeat(header.len()));

    // Rows
    for (i, post) in posts.iter().enumerate() {
        let name = if post.name.len() > max_name_len {
            format!("{}…", &post.name[..max_name_len - 1])
        } else {
            post.name.clone()
        };

        let tagline = if post.tagline.len() > max_tagline_len {
            format!("{}…", &post.tagline[..max_tagline_len - 1])
        } else {
            post.tagline.clone()
        };

        println!(
            "  {:<4} {:<width_name$} {:<width_tagline$} {:>6} {:>8}",
            i + 1,
            name,
            tagline,
            post.votes_count,
            post.comments_count,
            width_name = max_name_len,
            width_tagline = max_tagline_len,
        );
    }

    println!("\n  Total: {} launches", posts.len());
    println!("  Tip: Run `ph post <id>` for details, or `ph tui` for interactive mode.\n");
}
