//! `sprouts run` — manually trigger a handler.

use std::path::PathBuf;

use clap::Args as ClapArgs;

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

#[derive(ClapArgs)]
pub struct Args {
    /// The handler to run.
    handler: String,
    /// JSON payload for the handler (defaults to null).
    #[arg(long)]
    input: 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<()> {
    let sprout_id = session::resolve_sprout_id(args.id, &args.path)?;
    let payload = match &args.input {
        Some(s) => serde_json::from_str(s).map_err(|e| anyhow::anyhow!("invalid --input JSON: {e}"))?,
        None => serde_json::Value::Null,
    };
    let resp = session::authed(|u, t| api::run_sprout(u, t, &sprout_id, &args.handler, payload.clone()))?;
    let workflow = resp.get("workflow_id").and_then(|v| v.as_str()).unwrap_or("?");
    println!("Started `{}` ({workflow}). See `sprouts logs`.", args.handler);
    Ok(())
}
