//! `sprouts logs` — show a sprout's recent executions.

use std::path::PathBuf;

use clap::Args as ClapArgs;

use crate::api;
use crate::commands::session;

#[derive(ClapArgs)]
pub struct Args {
    /// Show one execution's captured program output (its id from the list).
    #[arg(long)]
    exec: Option<String>,
    /// The sprout id (defaults to the sprout named in ./sprout.toml).
    #[arg(long)]
    id: Option<String>,
    /// The sprout directory (used to resolve the name when `--id` is omitted).
    #[arg(long, default_value = ".")]
    path: PathBuf,
}

pub fn run(args: Args) -> anyhow::Result<()> {
    // `--exec <id>`: print that execution's captured stdout/stderr.
    if let Some(exec_id) = args.exec {
        let detail = session::authed(|u, t| api::execution(u, t, &exec_id))?;
        match detail.get("logs").and_then(|v| v.as_str()) {
            Some(body) if !body.is_empty() => print!("{body}"),
            _ => println!("(no output captured for this execution)"),
        }
        return Ok(());
    }

    let sprout_id = session::resolve_sprout_id(args.id, &args.path)?;
    let response = session::authed(|u, t| api::executions(u, t, &sprout_id))?;

    if response.executions.is_empty() {
        println!("No executions yet.");
        return Ok(());
    }

    for exec in response.executions {
        let trigger = exec.trigger_name.as_deref().unwrap_or("manual");
        println!(
            "{}  {:<9}  {:<16}  ({trigger})  {}",
            exec.started_at, exec.status, exec.handler, exec.id
        );
        if let Some(err) = exec.error_message {
            println!("    error: {err}");
        }
    }
    println!("\nRun `sprouts logs --exec <id>` to see an execution's captured output.");
    Ok(())
}
