# Core Lib Foundation Usage Patterns

## Overview
The core-lib foundation provides multiple usage patterns for different application needs, from simple configuration loading to complex multi-language applications with advanced state management.

## Pattern 1: Basic Configuration (Simplest)

**Best for**: Simple applications, quick prototypes, getting started

```rust
use core_lib::{load_design_system, get_configured_content_path, resolve_path};

fn main() -> Result<(), Box<dyn std::error::Error>> {
    // Load design system configuration
    let design_system = load_design_system()?;
    println!("Loaded theme: {}", design_system.theme.primary_color);
    
    // Get configured content paths
    let blog_path = get_configured_content_path("blog", "en");
    let pages_path = get_configured_content_path("page", "es");
    
    println!("Blog content: {}", blog_path);
    println!("Pages content: {}", pages_path);
    
    // Resolve environment-based paths
    let content_root = resolve_path("SITE_CONTENT_PATH", "content");
    let server_url = resolve_path("SITE_SERVER_CONTENT_URL", "/content");
    
    println!("Content root: {}", content_root);
    println!("Server URL: {}", server_url);
    
    Ok(())
}
```

**What you get automatically:**
- Environment-based configuration loading
- Design system configuration from TOML files
- Content path resolution with language support
- Environment variable resolution with defaults

**Environment setup:**
```bash
SITE_CONTENT_PATH=content
SITE_SERVER_CONTENT_URL=/content
DEFAULT_LANGUAGE=en
SUPPORTED_LANGUAGES=en,es,fr
```

## Pattern 2: Language-Agnostic i18n

**Best for**: Multi-language applications with dynamic language discovery

```rust
use core_lib::{
    discover_available_languages, get_default_language,
    is_supported_language, t, t_for_language,
    load_menu_for_language, load_footer_for_language
};

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    // Automatic language discovery from content structure
    let languages = discover_available_languages();
    let default_lang = get_default_language();
    
    println!("🌍 Discovered languages: {:?}", languages);
    println!("🎯 Default language: {}", default_lang);
    println!("📊 Total languages: {}", languages.len());
    
    // Translation system
    for lang in &languages {
        if is_supported_language(lang) {
            println!("\n--- {} ---", lang.to_uppercase());
            
            // Load translations
            let greeting = t_for_language("greeting", lang);
            let welcome = t_for_language("welcome-message", lang);
            
            println!("Greeting: {}", greeting);
            println!("Welcome: {}", welcome);
            
            // Load localized navigation
            let menu = load_menu_for_language(lang)?;
            println!("Menu items: {}", menu.menu.len());
            
            // Load localized footer
            let footer = load_footer_for_language(lang)?;
            println!("Footer sections: {}", footer.sections.len());
        }
    }
    
    Ok(())
}
```

**Directory structure expected:**
```
content/
├── locales/
│   ├── en/
│   │   ├── common.ftl
│   │   ├── menu.toml
│   │   └── footer.toml
│   ├── es/
│   │   ├── common.ftl
│   │   ├── menu.toml
│   │   └── footer.toml
│   └── fr/
│       ├── common.ftl
│       ├── menu.toml
│       └── footer.toml
└── blog/
    ├── en/
    ├── es/
    └── fr/
```

## Pattern 3: Content Management Integration

**Best for**: Applications with dynamic content types and content loading

```rust
use core_lib::{
    get_available_content_types, resolve_content_type_from_route,
    is_valid_content_type, get_content_type_display_name,
    load_content_by_type, load_content_by_slug,
    clear_content_type_cache
};

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    // Content type discovery
    let content_types = get_available_content_types();
    println!("📂 Available content types: {:?}", content_types);
    
    // Route-based content type resolution
    let routes = vec!["/blog/my-post", "/services/web-design", "/about"];
    
    for route in routes {
        if let Some(content_type) = resolve_content_type_from_route(route) {
            println!("\n🔗 Route: {} -> Type: {}", route, content_type);
            
            if is_valid_content_type(&content_type) {
                let display_name = get_content_type_display_name(&content_type);
                println!("   Display name: {}", display_name);
                
                // Load content by type
                match load_content_by_type(&content_type, "en").await {
                    Ok(content_index) => {
                        println!("   📋 Items: {}", content_index.items.len());
                        
                        // Load specific items
                        for item in content_index.items.iter().take(3) {
                            if let Some(content) = load_content_by_slug(&content_type, &item.slug, "en").await? {
                                println!("   📄 {}: {} words", content.title, content.content.len());
                            }
                        }
                    }
                    Err(e) => println!("   ❌ Error loading content: {}", e),
                }
            }
        }
    }
    
    // Clear cache if needed
    clear_content_type_cache();
    println!("\n🧹 Content type cache cleared");
    
    Ok(())
}
```

**Content configuration (content-kinds.toml):**
```toml
[blog]
title = "Blog Posts"
directory = "blog"
enabled = true
icon = "📝"
color = "#3B82F6"

[services]
title = "Services"
directory = "services"
enabled = true
icon = "🛠️"
color = "#10B981"

[page]
title = "Pages"
directory = "page"
enabled = true
is_default = true
icon = "📄"
color = "#6366F1"
```

## Pattern 4: Leptos State Management

**Best for**: Leptos applications needing comprehensive reactive state management

```rust
use core_lib::{
    AppStateProvider, LanguageProvider, ThemeProvider, ContentLoaderProvider,
    use_app_state, use_current_language, use_theme, use_auth_state,
    use_content_loader, use_route_state, AppState, ThemeState
};
use leptos::*;

#[component]
fn App() -> impl IntoView {
    view! {
        <AppStateProvider>
            <LanguageProvider>
                <ThemeProvider>
                    <ContentLoaderProvider>
                        <Router>
                            <Routes>
                                <Route path="/" view=HomePage />
                                <Route path="/dashboard" view=Dashboard />
                                <Route path="/settings" view=Settings />
                            </Routes>
                        </Router>
                    </ContentLoaderProvider>
                </ThemeProvider>
            </LanguageProvider>
        </AppStateProvider>
    }
}

#[component]
fn Dashboard() -> impl IntoView {
    let app_state = use_app_state();
    let current_lang = use_current_language();
    let theme_state = use_theme();
    let auth_state = use_auth_state();
    let content_loader = use_content_loader();
    let route_state = use_route_state();
    
    // Initialize dashboard
    create_effect(move |_| {
        app_state.update(|state| {
            state.ready = true;
            state.loading = false;
        });
    });
    
    // Language change effect
    create_effect(move |_| {
        let lang = current_lang.get();
        logging::log!("Language changed to: {}", lang);
        
        // Reload content for new language
        spawn_local(async move {
            content_loader.get().reload_for_language(&lang).await;
        });
    });
    
    view! {
        <div class="dashboard">
            <DashboardHeader />
            <DashboardContent />
            <DashboardControls />
        </div>
    }
}

#[component]
fn DashboardHeader() -> impl IntoView {
    let app_state = use_app_state();
    let current_lang = use_current_language();
    let theme_state = use_theme();
    
    view! {
        <header class="dashboard-header">
            <h1>{move || format!("Dashboard ({})", current_lang.get())}</h1>
            <div class="status">
                <span class=move || if app_state.get().ready { "ready" } else { "loading" }>
                    {move || if app_state.get().ready { "Ready" } else { "Loading..." }}
                </span>
                <span class="theme">
                    {move || format!("Theme: {}", theme_state.get().current_theme)}
                </span>
            </div>
        </header>
    }
}

#[component]
fn DashboardControls() -> impl IntoView {
    let app_state = use_app_state();
    let theme_state = use_theme();
    let auth_state = use_auth_state();
    
    let toggle_loading = move |_| {
        app_state.update(|state| state.loading = !state.loading);
    };
    
    let switch_theme = move |_| {
        theme_state.update(|state| {
            state.current_theme = if state.current_theme == "light" {
                "dark".to_string()
            } else {
                "light".to_string()
            };
            state.mode = if state.current_theme == "light" {
                core_lib::ThemeMode::Light
            } else {
                core_lib::ThemeMode::Dark
            };
        });
    };
    
    let logout = move |_| {
        auth_state.update(|state| {
            state.is_authenticated = false;
            state.user_info = None;
        });
    };

    view! {
        <div class="dashboard-controls">
            <button on:click=toggle_loading>
                {move || if app_state.get().loading { "Stop Loading" } else { "Start Loading" }}
            </button>
            <button on:click=switch_theme>
                {move || format!("Switch to {}", if theme_state.get().current_theme == "light" { "Dark" } else { "Light" })}
            </button>
            {move || if auth_state.get().is_authenticated {
                view! {
                    <button on:click=logout>"Logout"</button>
                }.into_view()
            } else {
                view! {
                    <span>"Not authenticated"</span>
                }.into_view()
            }}
        </div>
    }
}
```

## Pattern 5: Advanced Routing Integration

**Best for**: Applications with complex routing needs and language switching

```rust
use core_lib::{
    resolve_unified_route, get_localized_route, get_language_switch_url,
    get_menu_navigation, detect_language_from_path, extract_lang_and_path,
    RouteResolution, NavigationItem, NavigationTarget
};

#[derive(Debug)]
struct RoutingHandler {
    supported_languages: Vec<String>,
    default_language: String,
}

impl RoutingHandler {
    fn new() -> Self {
        Self {
            supported_languages: core_lib::get_supported_languages(),
            default_language: core_lib::get_default_language(),
        }
    }
    
    async fn handle_route(&self, path: &str) -> Result<String, Box<dyn std::error::Error>> {
        // Detect language from path
        let detected_lang = detect_language_from_path(path)
            .unwrap_or_else(|| self.default_language.clone());
        
        let (lang, clean_path) = extract_lang_and_path(path);
        
        println!("🔍 Analyzing route: {}", path);
        println!("   Language: {} (detected: {})", lang, detected_lang);
        println!("   Clean path: {}", clean_path);
        
        // Resolve the route
        match resolve_unified_route(path, &lang)? {
            RouteResolution::Content { component, content_type, slug, metadata, .. } => {
                println!("   ✅ Content route resolved");
                println!("      Component: {:?}", component);
                println!("      Type: {}", content_type);
                println!("      Slug: {}", slug);
                
                if let Some(meta) = metadata {
                    println!("      Title: {}", meta.title);
                    println!("      Description: {}", meta.description);
                }
                
                Ok(format!("Content: {} / {}", content_type, slug))
            }
            
            RouteResolution::Page { component, metadata, .. } => {
                println!("   ✅ Page route resolved");
                println!("      Component: {:?}", component);
                
                if let Some(meta) = metadata {
                    println!("      Title: {}", meta.title);
                }
                
                Ok(format!("Page: {:?}", component))
            }
            
            RouteResolution::NotFound => {
                println!("   ❌ Route not found");
                Ok("Not Found".to_string())
            }
        }
    }
    
    async fn generate_language_variants(&self, route_key: &str) -> Result<(), Box<dyn std::error::Error>> {
        println!("\n🌍 Language variants for '{}':", route_key);
        
        for lang in &self.supported_languages {
            match get_localized_route(route_key, lang) {
                Ok(localized_url) => {
                    println!("   {} -> {}", lang, localized_url);
                }
                Err(e) => {
                    println!("   {} -> Error: {}", lang, e);
                }
            }
        }
        
        Ok(())
    }
    
    async fn generate_navigation(&self, language: &str) -> Result<(), Box<dyn std::error::Error>> {
        println!("\n🧭 Navigation for '{}':", language);
        
        let navigation = get_menu_navigation(language)?;
        
        for item in navigation {
            println!("   {} -> {}", item.title, item.url);
            
            match item.target {
                NavigationTarget::Internal => println!("      (Internal link)"),
                NavigationTarget::External => println!("      (External link)"),
                NavigationTarget::Download => println!("      (Download link)"),
                NavigationTarget::Anchor => println!("      (Anchor link)"),
            }
            
            if !item.children.is_empty() {
                for child in &item.children {
                    println!("      └─ {} -> {}", child.title, child.url);
                }
            }
        }
        
        Ok(())
    }
    
    async fn generate_language_switches(&self, current_path: &str) -> Result<(), Box<dyn std::error::Error>> {
        println!("\n🔄 Language switches from '{}':", current_path);
        
        for lang in &self.supported_languages {
            match get_language_switch_url(current_path, lang) {
                Ok(switch_url) => {
                    println!("   Switch to {} -> {}", lang, switch_url);
                }
                Err(e) => {
                    println!("   Switch to {} -> Error: {}", lang, e);
                }
            }
        }
        
        Ok(())
    }
}

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let routing_handler = RoutingHandler::new();
    
    // Test various routes
    let test_routes = vec![
        "/",
        "/en",
        "/en/about", 
        "/es/servicios",
        "/fr/blog/mon-article",
        "/en/blog/my-first-post",
        "/invalid/route",
    ];
    
    for route in test_routes {
        routing_handler.handle_route(route).await?;
        println!();
    }
    
    // Generate language variants
    routing_handler.generate_language_variants("about").await?;
    routing_handler.generate_language_variants("services").await?;
    
    // Generate navigation for different languages
    routing_handler.generate_navigation("en").await?;
    routing_handler.generate_navigation("es").await?;
    
    // Generate language switches
    routing_handler.generate_language_switches("/en/about").await?;
    routing_handler.generate_language_switches("/es/blog/mi-articulo").await?;
    
    Ok(())
}
```

## Pattern 6: Build System Integration

**Best for**: Custom build systems and CI/CD integration

```rust
// build.rs
use std::env;
use std::path::Path;

fn main() -> Result<(), Box<dyn std::error::Error>> {
    println!("🏗️ Starting build process with core-lib integration");
    
    // Use core-lib build system
    match build_with_core_lib() {
        Ok(built) => {
            if built {
                println!("✅ Resources generated successfully");
            } else {
                println!("♻️  Using cached resources");
            }
        }
        Err(e) => {
            println!("❌ Build failed: {}", e);
            return Err(e);
        }
    }
    
    // Custom build steps
    custom_build_steps()?;
    
    println!("🎉 Build completed successfully");
    Ok(())
}

fn build_with_core_lib() -> Result<bool, Box<dyn std::error::Error>> {
    // Check for framework-only build
    if env::var("SKIP_SHARED_RESOURCES_BUILD").is_ok() {
        println!("⏭️  Skipping shared resources (framework-only build)");
        return Ok(false);
    }
    
    // Check if we have site configuration
    let manifest_dir = env::var("CARGO_MANIFEST_DIR")?;
    let project_root = Path::new(&manifest_dir)
        .parent()
        .ok_or("Cannot determine project root")?;
    
    let site_dir = project_root.join("site");
    if !site_dir.exists() {
        println!("📁 No site directory found - framework build mode");
        return Ok(false);
    }
    
    // Use smart cache system
    use core_lib::build::{generate_shared_resources_with_cache, SmartCache};
    
    // Force rebuild if requested
    if env::var("FORCE_REBUILD_CACHE").is_ok() {
        println!("🔄 Force rebuild requested - bypassing cache");
        core_lib::build::generate_shared_resources()?;
        return Ok(true);
    }
    
    // Use smart cache
    if core_lib::build::is_cache_available() {
        println!("💾 Using smart cache system");
        let built = generate_shared_resources_with_cache()?;
        
        if built {
            println!("   🔨 Generated new resources");
        } else {
            println!("   ⚡ Used cached resources");
        }
        
        return Ok(built);
    } else {
        println!("🚫 Cache not available - direct generation");
        core_lib::build::generate_shared_resources()?;
        return Ok(true);
    }
}

fn custom_build_steps() -> Result<(), Box<dyn std::error::Error>> {
    println!("🔧 Running custom build steps");
    
    // Check for required environment variables
    validate_environment()?;
    
    // Generate custom configuration
    generate_custom_config()?;
    
    // Process additional assets
    process_additional_assets()?;
    
    Ok(())
}

fn validate_environment() -> Result<(), Box<dyn std::error::Error>> {
    println!("   ✅ Validating environment variables");
    
    let required_vars = vec![
        "SITE_CONTENT_PATH",
        "SITE_SERVER_CONTENT_URL",
    ];
    
    for var in required_vars {
        match env::var(var) {
            Ok(value) => println!("      {} = {}", var, value),
            Err(_) => {
                let default = match var {
                    "SITE_CONTENT_PATH" => "content",
                    "SITE_SERVER_CONTENT_URL" => "/content",
                    _ => "",
                };
                println!("      {} = {} (default)", var, default);
                env::set_var(var, default);
            }
        }
    }
    
    Ok(())
}

fn generate_custom_config() -> Result<(), Box<dyn std::error::Error>> {
    println!("   🔧 Generating custom configuration");
    
    let out_dir = env::var("OUT_DIR")?;
    let config_path = Path::new(&out_dir).join("custom_config.rs");
    
    let config_content = r#"
// Auto-generated configuration
pub const BUILD_TIMESTAMP: &str = env!("BUILD_TIMESTAMP");
pub const GIT_COMMIT: &str = env!("GIT_COMMIT");
pub const BUILD_MODE: &str = env!("BUILD_MODE");

pub fn get_build_info() -> BuildInfo {
    BuildInfo {
        timestamp: BUILD_TIMESTAMP,
        commit: GIT_COMMIT, 
        mode: BUILD_MODE,
    }
}

#[derive(Debug, Clone)]
pub struct BuildInfo {
    pub timestamp: &'static str,
    pub commit: &'static str,
    pub mode: &'static str,
}
"#;
    
    std::fs::write(config_path, config_content)?;
    
    // Set build-time environment variables
    println!("cargo:rustc-env=BUILD_TIMESTAMP={}", chrono::Utc::now().to_rfc3339());
    
    if let Ok(commit) = std::process::Command::new("git")
        .args(&["rev-parse", "--short", "HEAD"])
        .output()
    {
        let commit_hash = String::from_utf8_lossy(&commit.stdout).trim().to_string();
        println!("cargo:rustc-env=GIT_COMMIT={}", commit_hash);
    } else {
        println!("cargo:rustc-env=GIT_COMMIT=unknown");
    }
    
    let build_mode = if cfg!(debug_assertions) { "debug" } else { "release" };
    println!("cargo:rustc-env=BUILD_MODE={}", build_mode);
    
    Ok(())
}

fn process_additional_assets() -> Result<(), Box<dyn std::error::Error>> {
    println!("   📦 Processing additional assets");
    
    let manifest_dir = env::var("CARGO_MANIFEST_DIR")?;
    let assets_dir = Path::new(&manifest_dir).join("assets");
    
    if assets_dir.exists() {
        println!("      Found assets directory: {}", assets_dir.display());
        
        // Process CSS files
        for entry in std::fs::read_dir(&assets_dir)? {
            let entry = entry?;
            let path = entry.path();
            
            if path.extension().and_then(|s| s.to_str()) == Some("css") {
                println!("      Processing CSS: {}", path.file_name().unwrap().to_str().unwrap());
                // CSS processing logic here
            }
        }
    }
    
    Ok(())
}
```

## Development vs Production Patterns

### Development Configuration
```rust
use core_lib::{get_debug_value, load_design_system};

fn setup_development() -> Result<(), Box<dyn std::error::Error>> {
    // Enable debug mode
    let debug_level = get_debug_value();
    
    if debug_level > 0 {
        println!("🐛 Debug mode enabled (level: {})", debug_level);
        
        // Setup development features
        if debug_level >= 2 {
            // Enable detailed logging
            println!("📝 Detailed logging enabled");
        }
        
        if debug_level >= 3 {
            // Enable route tracing
            println!("🔍 Route tracing enabled");
        }
    }
    
    // Load development design system
    let mut design_system = load_design_system()?;
    if cfg!(debug_assertions) {
        // Development tweaks
        design_system.development_mode = true;
    }
    
    Ok(())
}
```

### Production Configuration
```rust
use core_lib::{
    load_design_system, get_supported_languages,
    cache::{Cache, CacheConfig}
};

fn setup_production() -> Result<(), Box<dyn std::error::Error>> {
    // Production optimizations
    let cache_config = CacheConfig {
        max_entries: 10000,
        ttl_seconds: Some(3600), // 1 hour
        compress: true,
        persistent: true,
    };
    
    let cache = Cache::new(cache_config);
    
    // Preload all supported languages
    let languages = get_supported_languages();
    for lang in languages {
        // Preload critical resources
        let _menu = core_lib::load_menu_for_language(&lang)?;
        let _footer = core_lib::load_footer_for_language(&lang)?;
    }
    
    // Load production design system
    let design_system = load_design_system()?;
    assert!(!design_system.development_mode, "Development mode should be disabled in production");
    
    println!("🚀 Production setup completed");
    Ok(())
}
```

## Testing Patterns

### Unit Testing Core Functions
```rust
#[cfg(test)]
mod tests {
    use super::*;
    use core_lib::{
        discover_available_languages, resolve_content_type_from_route,
        get_configured_content_path
    };
    
    #[test]
    fn test_language_discovery() {
        let languages = discover_available_languages();
        assert!(!languages.is_empty(), "Should discover at least one language");
        assert!(languages.contains(&"en".to_string()), "Should include English");
    }
    
    #[test]
    fn test_content_type_resolution() {
        let test_cases = vec![
            ("/blog/my-post", Some("blog")),
            ("/services/web-design", Some("services")), 
            ("/about", Some("page")),
            ("/invalid/route", None),
        ];
        
        for (route, expected) in test_cases {
            let result = resolve_content_type_from_route(route);
            assert_eq!(result.as_deref(), expected, "Failed for route: {}", route);
        }
    }
    
    #[test]
    fn test_content_path_configuration() {
        std::env::set_var("SITE_CONTENT_PATH", "/tmp/test-content");
        
        let blog_path = get_configured_content_path("blog", "en");
        assert_eq!(blog_path, "/tmp/test-content/blog/en");
        
        let services_path = get_configured_content_path("services", "es");
        assert_eq!(services_path, "/tmp/test-content/services/es");
    }
}
```

### Integration Testing with Leptos
```rust
#[cfg(test)]
mod leptos_integration_tests {
    use super::*;
    use leptos::*;
    use core_lib::{AppStateProvider, use_app_state};
    
    #[test]
    fn test_app_state_provider() {
        let runtime = create_runtime();
        
        let (app_state, _) = run_scope(runtime, || {
            view! {
                <AppStateProvider>
                    <TestComponent />
                </AppStateProvider>
            }
        });
        
        // Test that state provider works correctly
        runtime.dispose();
    }
    
    #[component]
    fn TestComponent() -> impl IntoView {
        let app_state = use_app_state();
        
        create_effect(move |_| {
            let state = app_state.get();
            assert!(!state.ready); // Should start as not ready
        });
        
        view! {
            <div>"Test component"</div>
        }
    }
}
```

## Performance Optimization Patterns

### Caching Strategy
```rust
use core_lib::{Cache, CacheConfig, ContentCacheKey};

async fn setup_optimal_caching() -> Result<(), Box<dyn std::error::Error>> {
    // Multi-level cache configuration
    let l1_config = CacheConfig {
        max_entries: 100,
        ttl_seconds: Some(300), // 5 minutes
        compress: false,        // Fast access
        persistent: false,
    };
    
    let l2_config = CacheConfig {
        max_entries: 1000,
        ttl_seconds: Some(3600), // 1 hour
        compress: true,          // Space efficient
        persistent: true,        // Survives restarts
    };
    
    let l1_cache = Cache::new(l1_config);
    let l2_cache = Cache::new(l2_config);
    
    // Cache warming strategy
    let content_types = core_lib::get_available_content_types();
    let languages = core_lib::get_supported_languages();
    
    for content_type in content_types {
        for lang in &languages {
            // Warm L2 cache with content indexes
            let key = ContentCacheKey::new(&content_type, &lang, "index");
            if let Ok(content_index) = core_lib::load_content_by_type(&content_type, &lang).await {
                l2_cache.set(key, content_index).await?;
            }
        }
    }
    
    println!("🔥 Cache warmed successfully");
    Ok(())
}
```

## Error Handling Patterns

### Comprehensive Error Handling
```rust
use core_lib::{I18nError, routing::RoutingError};
use thiserror::Error;

#[derive(Error, Debug)]
pub enum AppError {
    #[error("Configuration error: {0}")]
    Config(String),
    
    #[error("i18n error: {0}")]
    I18n(#[from] I18nError),
    
    #[error("Routing error: {0}")]
    Routing(#[from] RoutingError),
    
    #[error("Content not found: {content_type}/{slug} in {language}")]
    ContentNotFound {
        content_type: String,
        slug: String,
        language: String,
    },
    
    #[error("Cache error: {0}")]
    Cache(String),
}

impl AppError {
    pub fn content_not_found(content_type: &str, slug: &str, language: &str) -> Self {
        Self::ContentNotFound {
            content_type: content_type.to_string(),
            slug: slug.to_string(),
            language: language.to_string(),
        }
    }
    
    pub fn is_recoverable(&self) -> bool {
        match self {
            AppError::Config(_) => false,
            AppError::I18n(_) => true,
            AppError::Routing(_) => true,
            AppError::ContentNotFound { .. } => true,
            AppError::Cache(_) => true,
        }
    }
}

async fn robust_content_loading(
    content_type: &str, 
    slug: &str, 
    language: &str
) -> Result<core_lib::ContentPost, AppError> {
    match core_lib::load_content_by_slug(content_type, slug, language).await {
        Ok(Some(content)) => Ok(content),
        Ok(None) => {
            // Try fallback language
            let default_lang = core_lib::get_default_language();
            if language != default_lang {
                match core_lib::load_content_by_slug(content_type, slug, &default_lang).await {
                    Ok(Some(content)) => {
                        logging::warn!("Content not found in {}, using {} fallback", language, default_lang);
                        Ok(content)
                    }
                    _ => Err(AppError::content_not_found(content_type, slug, language)),
                }
            } else {
                Err(AppError::content_not_found(content_type, slug, language))
            }
        }
        Err(e) => Err(AppError::Config(e.to_string())),
    }
}
```

## Choosing the Right Pattern

| Need | Pattern | Complexity | Use Case |
|------|---------|------------|----------|
| Simple config | Basic Configuration | Low | Getting started, prototypes |
| Multi-language | Language-Agnostic i18n | Medium | International applications |
| Dynamic content | Content Management | Medium | CMS, blogs, documentation |
| Reactive UI | Leptos State Management | High | Interactive web applications |
| Complex routing | Advanced Routing | High | Multi-language, complex navigation |
| Custom builds | Build Integration | High | CI/CD, custom tooling |

## Migration Between Patterns

Start simple and migrate to more complex patterns as needs grow:

1. **Start with Basic Configuration** for initial development
2. **Add Language-Agnostic i18n** when you need multiple languages
3. **Integrate Content Management** when you have dynamic content
4. **Use Leptos State Management** for interactive applications
5. **Implement Advanced Routing** for complex navigation needs
6. **Add Build Integration** for custom build processes

Each pattern builds on core-lib utilities, so migration is incremental and maintains compatibility with existing code.
