#![allow(dead_code)]
//! Infrastructure and component generation commands

use anyhow::Result;
use dialoguer::{Input, Select};
use std::process::Command;

/// Manage local infrastructure (Redis)
pub async fn manage_infrastructure() -> Result<()> {
    println!("\n╭─────────────────────────────────────────╮");
    println!("│  Infrastructure Management              │");
    println!("╰─────────────────────────────────────────╯\n");

    let docker_compose = std::path::PathBuf::from("docker-compose.yml");
    if !docker_compose.exists() {
        println!("  ❌ docker-compose.yml not found");
        println!("  This project may not have been initialized with 'mecha10 init'");
        return Ok(());
    }

    println!("  Checking Redis status...");
    let status_output = Command::new("docker")
        .args(["compose", "ps", "--format", "json", "redis"])
        .output();

    match status_output {
        Ok(output) if output.status.success() && !output.stdout.is_empty() => {
            let status_str = String::from_utf8_lossy(&output.stdout);
            if status_str.contains("running") || status_str.contains("Up") {
                println!("  ✅ Redis is already running on port 6380");
                return Ok(());
            }
        }
        _ => {}
    }

    println!("  🚀 Starting Redis service...");
    let start_result = Command::new("docker").args(["compose", "up", "-d", "redis"]).status();

    match start_result {
        Ok(status) if status.success() => {
            tokio::time::sleep(tokio::time::Duration::from_secs(2)).await;
            println!("  ✅ Redis started successfully on port 6380");
        }
        Ok(_) => {
            println!("  ❌ Failed to start Redis");
            println!("  Try running: mecha10 services start");
        }
        Err(e) => {
            println!("  ❌ Error starting Redis: {}", e);
            println!("  Make sure Docker is installed and running");
            println!("  Try running: mecha10 services start");
        }
    }

    Ok(())
}

/// Generate new component
pub async fn generate_component() -> Result<()> {
    println!("\n╭─────────────────────────────────────────╮");
    println!("│  Generate New Component                  │");
    println!("╰─────────────────────────────────────────╯\n");

    let component_types = vec![
        "Driver (sensor/actuator)",
        "Node (planner/controller)",
        "Config file",
        "Training environment",
        "Type definition",
    ];

    let selection = Select::new()
        .with_prompt("Select component type")
        .items(&component_types)
        .default(0)
        .interact()?;

    let component_name: String = Input::new().with_prompt("Component name").interact_text()?;

    println!("\n  Generating component...");

    match selection {
        0 => {
            let driver_path = format!("drivers/{}", component_name);
            println!("  Creating driver at: {}", driver_path);
            println!("  Command: mecha10 generate driver {}", component_name);
            println!("\n  ⚠ Use the standalone 'mecha10 generate' command for full generation");
        }
        1 => {
            let node_path = format!("nodes/{}", component_name);
            println!("  Creating node at: {}", node_path);
            println!("  Command: mecha10 generate node {}", component_name);
            println!("\n  ⚠ Use the standalone 'mecha10 generate' command for full generation");
        }
        2 => {
            let config_path = format!("config/{}.json", component_name);
            println!("  Creating config at: {}", config_path);
            println!("  Command: mecha10 generate config {}", component_name);
        }
        3 => {
            println!("  Creating training environment: {}", component_name);
            println!("  Command: mecha10 generate env {}", component_name);
        }
        4 => {
            println!("  Creating type definition: {}", component_name);
            println!("  Command: mecha10 generate type {}", component_name);
        }
        _ => {}
    }

    Ok(())
}
