//! Foundation CLI Commands
//!
//! CLI commands for discovering and managing foundation pages and components

/// Handle foundation list command
pub fn handle_foundation_list(filter: Option<&str>, format: &str) -> anyhow::Result<()> {
    // Discover foundation items using our new system
    let discovery = crate::build::foundation_discovery::discover_foundation_items()
        .map_err(|e| anyhow::anyhow!("{}", e))?;

    let items: Vec<_> = match filter {
        Some("page") => discovery
            .get_items_by_type(crate::build::foundation_discovery::FoundationItemType::Page),
        Some("component") => discovery
            .get_items_by_type(crate::build::foundation_discovery::FoundationItemType::Component),
        Some("utility") => discovery
            .get_items_by_type(crate::build::foundation_discovery::FoundationItemType::Utility),
        Some("type") => discovery
            .get_items_by_type(crate::build::foundation_discovery::FoundationItemType::Type),
        _ => {
            // All items
            let mut all_items = Vec::new();
            all_items.extend(discovery.pages.values());
            all_items.extend(discovery.components.values());
            all_items.extend(discovery.utilities.values());
            all_items.extend(discovery.types.values());
            all_items
        }
    };

    match format {
        "json" => {
            let json = serde_json::to_string_pretty(&items)?;
            println!("{}", json);
        }
        "markdown" => {
            println!("# Foundation Items\n");
            for item in &items {
                println!("## {} ({:?})\n", item.name, item.item_type);
                println!("**Module**: `{}`", item.module_path);
                println!("**File**: `{}`", item.file_path.display());
                if let Some(doc) = &item.documentation {
                    println!("**Description**: {}", doc);
                }
                println!("**Signature**: `{}`\n", item.signature);
            }
        }
        _ => {
            println!("┌─{:─<30}─┬─{:─<12}─┬─{:─<20}─┬─{:─<50}─┐", "", "", "", "");
            println!(
                "│ {:30} │ {:12} │ {:20} │ {:50} │",
                "Name", "Type", "Module", "Description"
            );
            println!("├─{:─<30}─┼─{:─<12}─┼─{:─<20}─┼─{:─<50}─┤", "", "", "", "");

            for item in &items {
                let type_str = match item.item_type {
                    crate::build::foundation_discovery::FoundationItemType::Page => "Page",
                    crate::build::foundation_discovery::FoundationItemType::Component => {
                        "Component"
                    }
                    crate::build::foundation_discovery::FoundationItemType::Utility => "Utility",
                    crate::build::foundation_discovery::FoundationItemType::Type => "Type",
                };

                let description = item
                    .documentation
                    .as_ref()
                    .map(|doc| doc.lines().next().unwrap_or("").trim())
                    .unwrap_or("No description");

                let truncated_desc = if description.len() > 48 {
                    format!("{}...", &description[..45])
                } else {
                    description.to_string()
                };

                let module_short = if item.module_path.len() > 18 {
                    format!("...{}", &item.module_path[item.module_path.len() - 15..])
                } else {
                    item.module_path.clone()
                };

                println!(
                    "│ {:30} │ {:12} │ {:20} │ {:50} │",
                    item.name, type_str, module_short, truncated_desc
                );
            }

            println!("└─{:─<30}─┴─{:─<12}─┴─{:─<20}─┴─{:─<50}─┘", "", "", "", "");
            println!("\nFound {} items", items.len());
        }
    }

    Ok(())
}

/// Handle foundation search command
pub fn handle_foundation_search(query: &str, include_docs: bool) -> anyhow::Result<()> {
    let discovery = crate::build::foundation_discovery::discover_foundation_items()
        .map_err(|e| anyhow::anyhow!("{}", e))?;
    let query_lower = query.to_lowercase();

    let mut matches = Vec::new();

    // Search in all items
    for item in discovery
        .pages
        .values()
        .chain(discovery.components.values())
        .chain(discovery.utilities.values())
        .chain(discovery.types.values())
    {
        let mut is_match = false;

        // Search in name
        if item.name.to_lowercase().contains(&query_lower) {
            is_match = true;
        }

        // Search in module path
        if item.module_path.to_lowercase().contains(&query_lower) {
            is_match = true;
        }

        // Search in documentation if requested
        if include_docs {
            if let Some(doc) = &item.documentation {
                if doc.to_lowercase().contains(&query_lower) {
                    is_match = true;
                }
            }
        }

        // Search in signature
        if item.signature.to_lowercase().contains(&query_lower) {
            is_match = true;
        }

        if is_match {
            matches.push(item);
        }
    }

    if matches.is_empty() {
        println!("❌ No matching foundation items found for '{}'", query);
        return Ok(());
    }

    println!("✅ Found {} matching items:\n", matches.len());

    for item in matches {
        let type_str = match item.item_type {
            crate::build::foundation_discovery::FoundationItemType::Page => "📄 Page",
            crate::build::foundation_discovery::FoundationItemType::Component => "🧩 Component",
            crate::build::foundation_discovery::FoundationItemType::Utility => "🛠️ Utility",
            crate::build::foundation_discovery::FoundationItemType::Type => "🏷️ Type",
        };

        println!("{} {}", type_str, item.name);
        println!("  Module: {}", item.module_path);
        if let Some(doc) = &item.documentation {
            println!("  Description: {}", doc.lines().next().unwrap_or("").trim());
        }
        println!("  Signature: {}\n", item.signature);
    }

    Ok(())
}

/// Handle foundation info command
pub fn handle_foundation_info(name: &str) -> anyhow::Result<()> {
    let discovery = crate::build::foundation_discovery::discover_foundation_items()
        .map_err(|e| anyhow::anyhow!("{}", e))?;

    if let Some(item) = discovery.get_item(name) {
        let type_str = match item.item_type {
            crate::build::foundation_discovery::FoundationItemType::Page => "📄 Page",
            crate::build::foundation_discovery::FoundationItemType::Component => "🧩 Component",
            crate::build::foundation_discovery::FoundationItemType::Utility => "🛠️ Utility",
            crate::build::foundation_discovery::FoundationItemType::Type => "🏷️ Type",
        };

        println!("# {} {}\n", type_str, item.name);
        println!("**Module**: `{}`", item.module_path);
        println!("**File**: `{}`", item.file_path.display());
        println!(
            "**Is Leptos Component**: {}",
            if item.is_component { "Yes" } else { "No" }
        );

        if let Some(doc) = &item.documentation {
            println!("\n**Documentation**:");
            for line in doc.lines() {
                println!("  {}", line);
            }
        }

        println!("\n**Signature**:");
        println!("```rust");
        println!("{}", item.signature);
        println!("```");

        if !item.dependencies.is_empty() {
            println!("\n**Dependencies**: {}", item.dependencies.join(", "));
        }
    } else {
        println!("❌ Foundation item '{}' not found", name);
        println!("💡 Use 'rustelo-tools foundation list' to see all available items");
    }

    Ok(())
}

/// Handle foundation clear cache command
pub fn handle_foundation_clear_cache() -> anyhow::Result<()> {
    // Clear the smart cache for foundation discovery
    if let Ok(cache) = crate::smart_cache::SmartCache::new("foundation-discovery") {
        let cache_root = cache.cache_root();
        if cache_root.exists() {
            std::fs::remove_dir_all(cache_root)?;
            println!("✅ Foundation discovery cache cleared");
        } else {
            println!("ℹ️ Foundation discovery cache was already empty");
        }
    } else {
        println!("⚠️ Could not access foundation discovery cache");
    }

    Ok(())
}

/// Handle foundation check updates command
pub fn handle_foundation_check_updates() -> anyhow::Result<()> {
    println!("🔍 Checking foundation for updates...");

    // Force fresh discovery by clearing cache first
    handle_foundation_clear_cache()?;

    // Run discovery to get latest state
    let discovery = crate::build::foundation_discovery::discover_foundation_items()
        .map_err(|e| anyhow::anyhow!("{}", e))?;

    let total_items = discovery.pages.len()
        + discovery.components.len()
        + discovery.utilities.len()
        + discovery.types.len();

    println!("✅ Foundation scan complete:");
    println!("  📄 Pages: {}", discovery.pages.len());
    println!("  🧩 Components: {}", discovery.components.len());
    println!("  🛠️ Utilities: {}", discovery.utilities.len());
    println!("  🏷️ Types: {}", discovery.types.len());
    println!("  📊 Total: {} items", total_items);
    println!("  🕒 Discovered at: {}", discovery.discovered_at);

    println!("\n💡 Use 'rustelo-tools foundation list' to see all available items");

    Ok(())
}

/// Test virtual resolution for a specific page or component
pub fn handle_virtual_resolution_test(item_name: &str, item_type: &str) -> anyhow::Result<()> {
    use crate::build::virtual_resolution::{ResolvedItemType, VirtualResolver};

    println!(
        "🧪 Testing virtual resolution for: {} (type: {})",
        item_name, item_type
    );

    let resolver = VirtualResolver::new().map_err(|e| anyhow::anyhow!("{}", e))?;
    let resolved_type = match item_type {
        "page" => ResolvedItemType::Page,
        "component" => ResolvedItemType::Component,
        "utility" => ResolvedItemType::Utility,
        "type" => ResolvedItemType::Type,
        _ => {
            println!("❌ Invalid item type. Use: page, component, utility, type");
            return Ok(());
        }
    };

    match resolver.resolve_item(item_name, resolved_type) {
        Ok(resolution) => {
            println!("✅ Virtual resolution successful!\n");

            println!("📋 Resolution Details:");
            println!("  Item: {}", resolution.item.name);
            println!("  Type: {:?}", resolution.item.item_type);
            println!("  Source: {:?}", resolution.item.source);
            println!("  File Path: {}", resolution.item.file_path.display());
            println!("  Import Path: {}", resolution.item.import_path);
            println!("  Needs Generation: {}", resolution.needs_generation);

            if !resolution.item.dependencies.is_empty() {
                println!(
                    "  Dependencies: {}",
                    resolution.item.dependencies.join(", ")
                );
            }

            println!("\n🔍 Resolution Trace:");
            for (i, step) in resolution.resolution_path.iter().enumerate() {
                let status = if step.found { "✅" } else { "❌" };
                println!(
                    "  {}. {} {:?} - {} ({})",
                    i + 1,
                    status,
                    step.source,
                    step.path_checked.display(),
                    step.reason
                );
            }

            if resolution.needs_generation {
                println!("\n🛠️ Generation Preview:");
                if let Some(content) = &resolution.item.content {
                    println!("```rust");
                    // Show first 10 lines
                    for (i, line) in content.lines().take(10).enumerate() {
                        println!("{:2}: {}", i + 1, line);
                    }
                    if content.lines().count() > 10 {
                        println!("... ({} more lines)", content.lines().count() - 10);
                    }
                    println!("```");
                }

                println!("\n💡 To apply this resolution, run:");
                println!("   cargo build  # Will automatically apply during build");
            } else {
                println!("\n✅ Item already exists, no generation needed");
            }
        }
        Err(e) => {
            println!("❌ Virtual resolution failed: {}", e);
        }
    }

    Ok(())
}
