use rustelo_core_lib::{
    resolve_unified_route, generate_ssr_render_component,
    discover_available_languages, get_configured_content_path,
    resolve_path, get_debug_value, RouteComponent,
    config::{ContentManageConfig, get_dynamic_content_config},
};
use std::collections::HashMap;

// Mock generated code for example purposes
// In a real application, these would be generated by build.rs

// Mock generated routes
pub fn get_all_routes() -> HashMap<String, String> {
    let mut routes = HashMap::new();
    routes.insert("/".to_string(), "HomePage".to_string());
    routes.insert("/about".to_string(), "AboutPage".to_string());
    routes
}

pub fn get_all_content_types() -> Vec<String> {
    vec!["blog".to_string(), "page".to_string()]
}

/// Example showing Rustelo's configuration-driven architecture
///
/// This demonstrates how TOML configuration files generate Rust components
/// following PAP (Project Architecture Principles): Configure, don't code.
fn main() -> Result<(), Box<dyn std::error::Error>> {
    println!("🏗️ Rustelo Configuration-Driven Architecture Example");
    println!("====================================================");
    println!();
    println!("This example shows how TOML configuration generates Rust code");
    println!("instead of writing components manually.");
    println!();

    // 1. Show configuration discovery
    demonstrate_configuration_discovery()?;

    // 2. Show generated components usage
    demonstrate_generated_components()?;

    // 3. Show content type generation
    demonstrate_content_type_generation().await?;

    // 4. Show build-time vs runtime boundaries
    demonstrate_build_time_generation()?;

    // Show the extension pattern
    demonstrate_custom_extension_pattern();

    println!("\n✅ Configuration-driven architecture demonstration completed!");
    println!("💡 To add new pages: Edit TOML files, run build, components appear automatically");
    Ok(())
}

fn setup_environment_config() -> Result<(), Box<dyn std::error::Error>> {
    println!("\n📁 Environment Configuration");
    println!("----------------------------");

    // Load content configuration from environment
    let content_config = ContentManageConfig::from_env();
    println!("Content root path: {}", content_config.root_path.display());
    println!("Server content URL: {}", content_config.server_content_url);

    // Load dynamic content configuration
    let dynamic_config = get_dynamic_content_config();
    println!("Asset mode: {:?}", dynamic_config.asset_mode);
    println!("Cache enabled: {}", dynamic_config.cache_enabled);
    println!("Hot reload: {}", dynamic_config.hot_reload);

    // Environment variable resolution with defaults
    let content_path = resolve_path("SITE_CONTENT_PATH", "content");
    let server_url = resolve_path("SITE_SERVER_CONTENT_URL", "/content");
    let devtools_path = resolve_path("SITE_DEVTOOLS_PATH", ".devtools");

    println!("Resolved paths:");
    println!("  Content: {}", content_path);
    println!("  Server URL: {}", server_url);
    println!("  Devtools: {}", devtools_path);

    Ok(())
}

fn setup_content_paths() -> Result<(), Box<dyn std::error::Error>> {
    println!("\n📂 Content Path Configuration");
    println!("-----------------------------");

    let content_types = vec!["blog", "services", "page", "portfolio"];
    let languages = vec!["en", "es", "fr"];

    println!("Content paths by type and language:");
    for content_type in &content_types {
        println!("  {}:", content_type);
        for lang in &languages {
            let path = get_configured_content_path(content_type, lang);
            println!("    {} -> {}", lang, path);
        }
    }

    Ok(())
}

fn setup_design_system() -> Result<(), Box<dyn std::error::Error>> {
    println!("\n🎨 Design System Configuration");
    println!("------------------------------");

    match load_design_system() {
        Ok(design_system) => {
            println!("Design system loaded successfully!");
            println!("Theme configuration:");
            println!("  Primary color: {}", design_system.theme.primary_color);
            println!("  Secondary color: {}", design_system.theme.secondary_color);
            println!("  Background color: {}", design_system.theme.background_color);
            println!("  Text color: {}", design_system.theme.text_color);

            println!("Typography:");
            println!("  Base size: {}", design_system.typography.base_size);
            println!("  Line height: {}", design_system.typography.line_height);
            println!("  Heading font: {}", design_system.typography.heading_font);
            println!("  Body font: {}", design_system.typography.body_font);

            println!("Spacing:");
            println!("  Base unit: {}", design_system.spacing.base_unit);
            println!("  Scale factor: {}", design_system.spacing.scale_factor);

            println!("Breakpoints:");
            for (name, width) in &design_system.breakpoints.breakpoints {
                println!("  {}: {}px", name, width);
            }
        }
        Err(e) => {
            println!("⚠️  Design system could not be loaded: {}", e);
            println!("   This is normal in WASM builds or when design-system.toml is not present");
        }
    }

    Ok(())
}

async fn setup_navigation_resources() -> Result<(), Box<dyn std::error::Error>> {
    println!("\n🧭 Navigation Resources Configuration");
    println!("------------------------------------");

    let languages = vec!["en", "es", "fr"];

    for lang in &languages {
        println!("Loading resources for {}:", lang);

        // Load menu configuration
        match load_menu_for_language(lang) {
            Ok(menu_config) => {
                println!("  ✅ Menu: {} items", menu_config.menu.len());
                for (i, item) in menu_config.menu.iter().take(3).enumerate() {
                    println!("    {}. {} -> {}", i + 1, item.title, item.url);
                }
                if menu_config.menu.len() > 3 {
                    println!("    ... and {} more items", menu_config.menu.len() - 3);
                }
            }
            Err(e) => {
                println!("  ❌ Menu loading failed: {}", e);
            }
        }

        // Load footer configuration
        match load_footer_for_language(lang) {
            Ok(footer_config) => {
                println!("  ✅ Footer: {} sections", footer_config.sections.len());
                for section in &footer_config.sections {
                    println!("    - {} ({} links)", section.title, section.links.len());
                }
            }
            Err(e) => {
                println!("  ❌ Footer loading failed: {}", e);
            }
        }

        println!();
    }

    Ok(())
}

fn setup_debug_mode() -> Result<(), Box<dyn std::error::Error>> {
    println!("\n🐛 Debug Configuration");
    println!("----------------------");

    let debug_level = get_debug_value();

    match debug_level {
        0 => println!("Debug mode: Disabled"),
        1 => println!("Debug mode: Main debug output"),
        2 => println!("Debug mode: Complementary debug output"),
        3 => println!("Debug mode: Route lookup and rendering traces"),
        4 => println!("Debug mode: Deep trace mode"),
        level => println!("Debug mode: Maximum verbosity (level {})", level),
    }

    if debug_level > 0 {
        println!("Debug features enabled:");
        println!("  ✅ Basic logging");

        if debug_level >= 2 {
            println!("  ✅ Detailed logging");
        }

        if debug_level >= 3 {
            println!("  ✅ Route tracing");
        }

        if debug_level >= 4 {
            println!("  ✅ Deep tracing");
        }

        println!("💡 Set SITE_DEBUG=0 to disable debug output");
        println!("💡 Set SITE_DEBUG=1 for basic debug info");
        println!("💡 Set SITE_DEBUG=2+ for more verbose output");
    }

    Ok(())
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_path_resolution() {
        // Test with environment variable set
        std::env::set_var("TEST_VAR", "/custom/path");
        let path = resolve_path("TEST_VAR", "/default/path");
        assert_eq!(path, "/custom/path");

        // Test with default fallback
        std::env::remove_var("TEST_VAR");
        let path = resolve_path("TEST_VAR", "/default/path");
        assert_eq!(path, "/default/path");
    }

    #[test]
    fn test_content_path_generation() {
        std::env::set_var("SITE_CONTENT_PATH", "/test/content");

        let blog_en_path = get_configured_content_path("blog", "en");
        assert_eq!(blog_en_path, "/test/content/blog/en");

        let services_es_path = get_configured_content_path("services", "es");
        assert_eq!(services_es_path, "/test/content/services/es");
    }

    #[test]
    fn test_debug_value_parsing() {
        std::env::set_var("SITE_DEBUG", "2");
        let debug_level = get_debug_value();
        assert_eq!(debug_level, 2);

        std::env::set_var("SITE_DEBUG", "invalid");
        let debug_level = get_debug_value();
        assert_eq!(debug_level, 0); // Should default to 0 for invalid values

        std::env::remove_var("SITE_DEBUG");
        let debug_level = get_debug_value();
        assert_eq!(debug_level, 0); // Should default to 0 when not set
    }
}
