// Generated files from build.rs
include!(concat!(env!("OUT_DIR"), "/node_registry.rs"));
include!(concat!(env!("OUT_DIR"), "/embedded.rs"));

use anyhow::Result;
use mecha10_core::prelude::*;

#[tokio::main]
async fn main() -> Result<()> {
    init_logging();

    info!("🤖 {{project_name}} starting...");

    // Parse command
    match std::env::args().nth(1).as_deref() {
        Some("run") => run_all_nodes().await,
        Some("node") => {
            let name = std::env::args()
                .nth(2)
                .ok_or_else(|| anyhow::anyhow!("Node name required"))?;
            run_single_node(&name).await
        }
        Some("list") => list_nodes(),
        Some("info") => show_info(),
        _ => print_help(),
    }
}

async fn run_all_nodes() -> Result<()> {
    info!("Starting all enabled nodes (target: {})...", RUN_TARGET);

    if ENABLED_NODES.is_empty() {
        info!("No nodes enabled. Add nodes with: mecha10 add <component>");
        return Ok(());
    }

    for node_name in ENABLED_NODES {
        info!("▶️  {}", node_name);
    }

    info!("✅ All nodes started");
    Ok(())
}

async fn run_single_node(name: &str) -> Result<()> {
    info!("Starting node: {}", name);

    // Call generated dispatcher function
    run_node(name).await
}

fn list_nodes() -> Result<()> {
    println!("Enabled nodes:");
    if ENABLED_NODES.is_empty() {
        println!("  (none - add nodes with: mecha10 add <component>)");
    } else {
        for node in ENABLED_NODES {
            println!("  - {}", node);
        }
    }
    Ok(())
}

fn show_info() -> Result<()> {
    println!("{{project_name}} v0.1.0\n");

    println!("Run Target: {}", RUN_TARGET);
    println!();

    println!("Enabled Nodes:");
    if ENABLED_NODES.is_empty() {
        println!("  (none)");
    } else {
        for node in ENABLED_NODES {
            println!("  - {}", node);
        }
    }

    println!("\nEmbedded Configs:");
    let configs = Embedded::list_configs();
    if configs.is_empty() {
        println!("  (none)");
    } else {
        for config in configs {
            println!("  - {}", config);
        }
    }

    println!("\nEmbedded Models:");
    let models = Embedded::list_models();
    if models.is_empty() {
        println!("  (none)");
    } else {
        for model in models {
            println!("  - {}", model);
        }
    }

    Ok(())
}

fn print_help() -> Result<()> {
    eprintln!("{{project_name}} v0.1.0\n");
    eprintln!("Usage:");
    eprintln!("  {{project_name}} run              Start all enabled nodes");
    eprintln!("  {{project_name}} node <name>      Start single node");
    eprintln!("  {{project_name}} list             List enabled nodes");
    eprintln!("  {{project_name}} info             Show project info");
    eprintln!("  {{project_name}} --help           Show this help");
    Ok(())
}
