use rustelo_core_lib::{
    discover_available_languages, get_default_language, get_supported_languages,
    is_supported_language, supported_language_count, t, t_for_language,
    localize_url, url_localizer, extract_language, clean_path,
};

/// Example showing how to set up and use the core-lib i18n system
fn main() -> Result<(), Box<dyn std::error::Error>> {
    println!("🌍 Core Lib i18n System Setup Example");
    println!("=====================================");
    
    // Language discovery
    demonstrate_language_discovery()?;
    
    // Translation system
    demonstrate_translations().await?;
    
    // URL localization
    demonstrate_url_localization()?;
    
    // Language detection
    demonstrate_language_detection()?;
    
    println!("\n✅ i18n system demonstration completed successfully!");
    Ok(())
}

fn demonstrate_language_discovery() -> Result<(), Box<dyn std::error::Error>> {
    println!("\n🔍 Language Discovery");
    println!("--------------------");
    
    // Automatic language discovery from content structure
    let discovered_languages = discover_available_languages();
    let default_language = get_default_language();
    let supported_languages = get_supported_languages();
    let language_count = supported_language_count();
    
    println!("Discovered languages: {:?}", discovered_languages);
    println!("Default language: {}", default_language);
    println!("Supported languages: {:?}", supported_languages);
    println!("Total language count: {}", language_count);
    
    // Test language support
    let test_languages = vec!["en", "es", "fr", "de", "invalid"];
    println!("\nLanguage support check:");
    for lang in test_languages {
        let is_supported = is_supported_language(lang);
        let status = if is_supported { "✅" } else { "❌" };
        println!("  {} {}: {}", status, lang, if is_supported { "supported" } else { "not supported" });
    }
    
    Ok(())
}

async fn demonstrate_translations() -> Result<(), Box<dyn std::error::Error>> {
    println!("\n📝 Translation System");
    println!("--------------------");
    
    let languages = get_supported_languages();
    let translation_keys = vec![
        "greeting",
        "welcome-message", 
        "navigation-home",
        "navigation-about",
        "navigation-services",
        "footer-copyright",
        "button-learn-more",
        "contact-email-label",
    ];
    
    println!("Testing translations across languages:");
    
    for lang in languages {
        println!("\n🏳️  {} ({})", get_language_display_name(lang), lang.to_uppercase());
        println!("   {}", "─".repeat(20));
        
        for key in &translation_keys {
            let translation = t_for_language(key, lang);
            println!("   {}: {}", key, translation);
        }
    }
    
    // Demonstrate default language fallback
    println!("\n🔄 Default Language Fallback");
    println!("----------------------------");
    
    // Try to get a translation using the t() function (uses default language)
    let default_greeting = t("greeting");
    println!("Default language greeting: {}", default_greeting);
    
    // Try a key that might not exist
    let missing_key = t_for_language("non-existent-key", "en");
    println!("Missing key result: {}", missing_key);
    
    Ok(())
}

fn demonstrate_url_localization() -> Result<(), Box<dyn std::error::Error>> {
    println!("\n🔗 URL Localization");
    println!("-------------------");
    
    let base_urls = vec![
        "/",
        "/about",
        "/services", 
        "/blog",
        "/contact",
        "/blog/my-first-post",
    ];
    
    let languages = get_supported_languages();
    
    println!("URL localization matrix:");
    println!("Path                 | {}", languages.join("           | "));
    println!("{}", "-".repeat(20 + (languages.len() * 14)));
    
    for url in &base_urls {
        print!("{:<20} |", url);
        
        for lang in languages {
            let localized = localize_url(url, lang);
            print!(" {:<12} |", localized);
        }
        println!();
    }
    
    // Demonstrate URL localizer utility
    println!("\n🛠️  URL Localizer Utility");
    println!("------------------------");
    
    let localizer = url_localizer();
    
    for url in &base_urls {
        println!("Base URL: {}", url);
        for lang in languages {
            let localized = localizer.localize(url, lang);
            println!("  {} -> {}", lang, localized);
        }
        println!();
    }
    
    Ok(())
}

fn demonstrate_language_detection() -> Result<(), Box<dyn std::error::Error>> {
    println!("\n🎯 Language Detection");
    println!("--------------------");
    
    let test_urls = vec![
        "/",
        "/en",
        "/en/about",
        "/es/servicios",
        "/fr/blog/mon-article",
        "/en/blog/my-first-post",
        "/invalid/path",
        "/services", // No language prefix
        "/es/", // Language with trailing slash
    ];
    
    println!("Language detection from URLs:");
    for url in &test_urls {
        let detected_lang = extract_language(url);
        let cleaned_path = clean_path(url);
        
        if !detected_lang.is_empty() {
            println!("  {} -> Language: {}, Path: {}", url, detected_lang, cleaned_path);
        } else {
            println!("  {} -> No language detected, Path: {}", url, cleaned_path);
        }
    }
    
    // Demonstrate path cleaning
    println!("\n🧹 Path Cleaning");
    println!("----------------");
    
    let messy_paths = vec![
        "/en/about/",
        "//es//servicios//",
        "/fr/blog/article/",
        "///multiple///slashes///",
        "/clean/path",
    ];
    
    for path in &messy_paths {
        let cleaned = clean_path(path);
        println!("  {} -> {}", path, cleaned);
    }
    
    Ok(())
}

fn get_language_display_name(lang: &str) -> &str {
    match lang {
        "en" => "English",
        "es" => "Español", 
        "fr" => "Français",
        "de" => "Deutsch",
        "it" => "Italiano",
        "pt" => "Português",
        "ja" => "日本語",
        "zh" => "中文",
        _ => "Unknown",
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::collections::HashMap;
    
    #[test]
    fn test_language_discovery() {
        let languages = discover_available_languages();
        assert!(!languages.is_empty(), "Should discover at least one language");
        
        let default = get_default_language();
        assert!(!default.is_empty(), "Default language should not be empty");
        
        let count = supported_language_count();
        assert_eq!(count, languages.len(), "Count should match discovered languages length");
    }
    
    #[test] 
    fn test_language_support() {
        assert!(is_supported_language("en"), "English should be supported");
        assert!(!is_supported_language("invalid"), "Invalid language should not be supported");
        assert!(!is_supported_language(""), "Empty string should not be supported");
    }
    
    #[test]
    fn test_url_localization() {
        let test_cases = vec![
            ("/about", "en", "/en/about"),
            ("/services", "es", "/es/services"),
            ("/", "fr", "/fr"),
        ];
        
        for (url, lang, expected) in test_cases {
            let result = localize_url(url, lang);
            assert_eq!(result, expected, "Failed for URL: {} with language: {}", url, lang);
        }
    }
    
    #[test]
    fn test_language_extraction() {
        let test_cases = vec![
            ("/en/about", Some("en".to_string())),
            ("/es/servicios", Some("es".to_string())),
            ("/fr/blog/article", Some("fr".to_string())),
            ("/about", None),
            ("/", None),
            ("", None),
        ];
        
        for (url, expected) in test_cases {
            let result = extract_language(url);
            assert_eq!(result, expected, "Failed for URL: {}", url);
        }
    }
    
    #[test]
    fn test_path_cleaning() {
        let test_cases = vec![
            ("/path/", "/path"),
            ("//double//slash//", "/double/slash"),
            ("/normal/path", "/normal/path"),
            ("///", "/"),
            ("", ""),
        ];
        
        for (input, expected) in test_cases {
            let result = clean_path(input);
            assert_eq!(result, expected, "Failed for input: {}", input);
        }
    }
    
    #[tokio::test]
    async fn test_translation_fallback() {
        // Test that translation functions handle missing keys gracefully
        let result = t_for_language("non-existent-key", "en");
        assert!(!result.is_empty(), "Should return some fallback for missing keys");
        
        let default_result = t("greeting");
        assert!(!default_result.is_empty(), "Default translation should work");
    }
    
    #[test]
    fn test_url_localizer_utility() {
        let localizer = url_localizer();
        
        let result = localizer.localize("/about", "es");
        assert!(result.contains("es"), "Localized URL should contain language code");
        
        let result = localizer.localize("/", "fr");
        assert!(result.contains("fr"), "Root URL should be properly localized");
    }
}