//! Node command handler
//!
//! Runs bundled nodes directly. This is an internal command used by standalone mode
//! to avoid requiring users to build their project.

use crate::commands::NodeArgs;
use anyhow::Result;
use tracing::info;

/// Available bundled nodes
const BUNDLED_NODES: &[&str] = &[
    "behavior-executor",
    "diagnostics-node",
    "image-classifier",
    "imu",
    "listener",
    "llm-command",
    "motor",
    "object-detector",
    "simulation-bridge",
    "speaker",
    "teleop",
    "websocket-bridge",
];

/// Handle the node command - runs a bundled node directly
pub async fn handle_node(args: &NodeArgs) -> Result<()> {
    let name = &args.name;

    if !BUNDLED_NODES.contains(&name.as_str()) {
        anyhow::bail!(
            "Unknown node: '{}'. Available nodes: {}",
            name,
            BUNDLED_NODES.join(", ")
        );
    }

    info!("Starting bundled node: {}", name);
    run_bundled_node(name).await
}

/// Run a bundled node by name
async fn run_bundled_node(name: &str) -> Result<()> {
    match name {
        "behavior-executor" => mecha10_nodes_behavior_executor::run()
            .await
            .map_err(|e| anyhow::anyhow!("{}", e)),
        "diagnostics-node" => mecha10_nodes_diagnostics::run()
            .await
            .map_err(|e| anyhow::anyhow!("{}", e)),
        "image-classifier" => mecha10_nodes_image_classifier::run()
            .await
            .map_err(|e| anyhow::anyhow!("{}", e)),
        "imu" => mecha10_nodes_imu::run().await.map_err(|e| anyhow::anyhow!("{}", e)),
        "listener" => mecha10_nodes_listener::run()
            .await
            .map_err(|e| anyhow::anyhow!("{}", e)),
        "llm-command" => mecha10_nodes_llm_command::run()
            .await
            .map_err(|e| anyhow::anyhow!("{}", e)),
        "motor" => mecha10_nodes_motor::run().await.map_err(|e| anyhow::anyhow!("{}", e)),
        "object-detector" => mecha10_nodes_object_detector::run()
            .await
            .map_err(|e| anyhow::anyhow!("{}", e)),
        "simulation-bridge" => mecha10_nodes_simulation_bridge::run()
            .await
            .map_err(|e| anyhow::anyhow!("{}", e)),
        "speaker" => mecha10_nodes_speaker::run().await.map_err(|e| anyhow::anyhow!("{}", e)),
        "teleop" => mecha10_nodes_teleop::run().await.map_err(|e| anyhow::anyhow!("{}", e)),
        "websocket-bridge" => mecha10_nodes_websocket_bridge::run()
            .await
            .map_err(|e| anyhow::anyhow!("{}", e)),
        _ => Err(anyhow::anyhow!("Unknown node: {}", name)),
    }
}
