//! Environment listing
//!
//! Functions for listing available simulation environments.

use crate::sim::{EnvironmentSelector, RobotProfile};
use anyhow::Result;
use std::path::Path;

/// List available environments matching robot configuration
pub fn list_environments(config_path: &Path, verbose: bool) -> Result<()> {
    let selector = EnvironmentSelector::new()?;
    let profile = RobotProfile::from_config_file(config_path)?;

    println!("🤖 Analyzing robot configuration...\n");
    println!("Robot Profile:");
    println!("  Platform: {}", profile.platform);
    println!("  Sensors: {}", profile.sensors.join(", "));
    println!(
        "  Task Nodes: {}",
        profile
            .task_nodes
            .iter()
            .map(|n| n.name.as_str())
            .collect::<Vec<_>>()
            .join(", ")
    );
    println!("  Capabilities: {}", profile.capabilities.join(", "));
    println!();

    let matches = selector.select_environments(&profile, 10)?;

    if matches.is_empty() {
        println!("❌ No matching environments found.");
        println!("\nTry:");
        println!("  - Adding more sensors to your robot");
        println!("  - Checking sensor requirements in catalog");
        return Ok(());
    }

    println!("Matching Environments (ranked by relevance):\n");

    for (i, env_match) in matches.iter().enumerate() {
        let stars = match env_match.score {
            s if s >= 40 => "★★★★★",
            s if s >= 30 => "★★★★☆",
            s if s >= 20 => "★★★☆☆",
            s if s >= 10 => "★★☆☆☆",
            _ => "★☆☆☆☆",
        };

        println!(
            "{}. {} (score: {}) {}",
            i + 1,
            env_match.environment.name,
            env_match.score,
            stars
        );
        println!("   ID: {}", env_match.environment.id);
        println!("   Path: {}", env_match.environment.path);
        println!("   Difficulty: {}", env_match.environment.difficulty);

        if verbose {
            println!("   Reasons:");
            for reason in &env_match.reasons {
                println!("     - {}", reason);
            }
        }

        println!();
    }

    Ok(())
}
