//! # Rustelo Core Crate
//!
//! Core runtime functionality with build-time generation for the Rustelo
//! framework.
//!
//! This crate combines:
//! - All pure types from core-types (re-exported)
//! - Build-time code generation and resource embedding
//! - Generated route and content type definitions
//!
//! ## Architecture
//!
//! - Depends on core-types for pure runtime types
//! - Uses tools crate at build-time for code generation
//! - Provides the final, complete core API with generated code
//!
//! ## Future Crate Organization (Phase 2A)
//!
//! This crate is being prepared for modularization into focused sub-crates.
//! See module documentation for extraction status and dependencies.
//!
//! ### Ready for Extraction ✅
//! - **routing** → `rustelo_routing` (Phase 1 complete, zero circular deps)
//!
//! ### Needs Preparation ⚠️
//! - **content** → `rustelo_content` (depends on routing, i18n)
//! - **auth** → `rustelo_auth` (feature-gated, optional)
//! - **i18n** → `rustelo_i18n` (widely used, extract carefully)
//!
//! ### Stays in Core ⚡
//! - **registration** - Plugin system (core framework feature)
//! - **integrity** - Framework protection (core framework feature)
//! - **layered_override** - Template system (core framework feature)
//! - **mergeable_configs** - Config merging (core framework feature)

#![allow(unused_imports)]
#![allow(dead_code)]
#![recursion_limit = "256"]

// ============================================================================
// CORE FRAMEWORK MODULES (stay in rustelo_core_lib)
// ============================================================================

// Layered override system for configuration and component resolution
pub mod layered_override;

// Mergeable configuration types for the layered system
pub mod mergeable_configs;

// Framework integrity protection system
pub mod integrity;

// Plugin and resource registration system (replaces conditional compilation)
pub mod registration;

// ============================================================================
// FUTURE EXTRACTABLE MODULES
// ============================================================================
// These modules are structured for future crate extraction.
// See each module's documentation for extraction readiness and dependencies.

// Routing system (READY FOR EXTRACTION - Phase 1 complete ✅)
// Future crate: rustelo_routing
// Dependencies: rustelo_core_types, rustelo_utils, leptos
// Status: Zero circular dependencies, clean public API
pub mod routing;

// Content management (NEEDS PREP - depends on routing, i18n ⚠️)
// Future crate: rustelo_content
// Dependencies: rustelo_routing, rustelo_i18n, rustelo_core_types
// Status: Well-defined but coupled to internal modules
pub mod content;

// Authentication and authorization (OPTIONAL - feature-gated)
// Future crate: rustelo_auth (or stay as feature in core_lib)
// Dependencies: rustelo_core_types, jwt libs
// Status: Optional feature, can be extracted later
pub mod auth;

// Internationalization (NEEDS PREP - widely used ⚠️)
// Future crate: rustelo_i18n
// Dependencies: fluent, rustelo_core_types
// Status: Core dependency for routing and content, extract carefully
pub mod fluent;
pub mod i18n;

// ============================================================================
// SUPPORTING MODULES (decision pending on extraction)
// ============================================================================

// Caching system (could stay or extract to rustelo_cache)
pub mod cache;

// Content type resolution (likely stays with content)
pub mod content_resolver;

// Category and tag management (part of content system)
pub mod categories;

// Configuration management (core framework, likely stays)
pub mod config;

// Type definitions (likely stays or moves to core_types)
pub mod defs;

// Metadata preloading (performance optimization, likely stays)
pub mod meta_preloader;

// Path resolution (core framework feature, likely stays)
pub mod path_resolution;

// Resource management (part of registration system)
pub mod resources;

// Application state — uses Leptos reactive signals; not needed for htmx-ssr.
#[cfg(any(target_arch = "wasm32", feature = "leptos-hydration"))]
pub mod state;

// Theme system (part of design system, likely stays)
pub mod theme;

// Utility functions (general purpose, likely stays)
pub mod utils;

// ============================================================================
// RE-EXPORTS AND PUBLIC API
// ============================================================================

// Re-export everything from core-types for a unified API, except config and
// routing which we override with generated code Note: RouteComponent and
// RouteConfigToml are provided by generated code only
// Re-export main abstract types for easy access
pub use cache::{Cache, CacheConfig as LocalCacheConfig, CacheEntry, CacheStats, ContentCacheKey};
pub use categories::{get_all_categories, get_all_tags, load_meta_config, MetaConfig};
pub use config::*;
// Re-export unified content config
pub use config::{get_dynamic_content_config, AssetMode, DynamicContentConfig};
// Re-export content resolver
pub use content_resolver::{
    clear_content_type_cache, get_available_content_types, get_content_type_display_name,
    is_valid_content_type, resolve_content_type_from_route,
};
// Re-export pure traits for dependency injection
pub use defs::{
    BreakpointConfig, ColorConfig, DesignSystemConfig, FooterConfig, FooterLink, FooterSection,
    LogoConfig, MenuConfig, MenuItem, SimpleMenuConfig, SimpleMenuItem, SocialLinkConfig,
    SpacingConfig, ThemeConfig as LocalThemeConfig, Translations, TypographyConfig,
};
// Text utilities now re-exported at top of file
/// Text container structure for internationalization
pub use fluent::HashMapTexts as Texts;
// pub use rustelo_pages::UnifiedNotFoundPage;

// Re-export fluent functionality
pub use fluent::{
    load_content_by_slug, load_content_by_type, load_content_index, load_markdown_content,
    load_texts_from_ftl, process_markdown_file, rewrite_content_image_paths, ComponentKeys,
    ContentIndex, ContentPost, FtlKeys, FtlParseResult, FtlParser, HashMapTexts, MarkdownPage,
    MarkdownProcessor, PageKeys, TranslationKey, TranslationSection,
};
pub use i18n::{
    build_page_content_patterns,
    // Dynamic language discovery functions
    discover_available_languages,
    get_default_language,
    get_supported_languages,
    is_supported_language,
    localize_url,
    supported_language_count,
    t,
    t_for_language,
    I18nError,
    PageContentBuilder,
    PageTranslator,
    SsrTranslator,
};
// Re-export framework integrity protection types
pub use integrity::{
    FrameworkManifest, ImprovementSuggestion, IntegrityError, IntegrityValidator,
    IntegrityViolation, IntegrityWarning, RepairResult, UpdateSafety, ValidationResult,
    ValidationSummary, ViolationCategory, ViolationSeverity,
};
pub use meta_preloader::{
    are_meta_configs_loaded, get_category_emoji, get_tag_emoji, init_meta_preloader,
    refresh_meta_configs, MetaLoadingState,
};
// Page generation macros removed - using build-time generation instead
// Components are now generated in build.rs

// Re-export registration API for resource management
pub use registration::{
    get_footer, get_ftl, get_menu, get_theme, list_languages, list_pages, list_themes,
    load_resources_from_config, register_contributor, register_footer, register_ftl, register_menu,
    register_theme, PageContributor, RegistrationError, ResourceContributor,
};
// Traits from core-types are already re-exported above via pub use rustelo_core_types::*;
pub use resources::*;
// Re-export generated access functions and traits
pub use routing::generated_access::{
    create_content_kind_registry, generated_config, get_all_content_types,
    get_enabled_content_types, register_content_kind_registry, register_server_content_url,
    GeneratedConfigAccess, GeneratedContentAccess,
};
// Re-export utility functions
pub use routing::url_generation::get_content_type_from_component;
pub use routing::{
    // Modern unified routing engine exports (only include what exists)
    get_language_switch_url,
    get_menu_navigation,
    get_routing_config,
    get_toml_routes_for_language,
    resolve_unified_route,
    EngineRouteMetadata,
    NavigationItem as LocalNavigationItem,
    NavigationTarget,
    PageComponent,
    RouteMetadata as LocalRouteMetadata,
    RouteResolution,
};
pub use rustelo_core_types::*;
// Re-export utils for easy access
pub use rustelo_utils::{normalize_category, normalize_tag, title_to_slug, to_slug};
#[cfg(any(target_arch = "wasm32", feature = "leptos-hydration"))]
pub use state::{
    use_app_state, use_app_state_summary, use_auth_state, use_content_loader,
    use_content_loading_state, use_current_language, use_i18n_content, use_language,
    use_language_switcher, use_menu_routes, use_meta_state, use_route_state, use_theme,
    use_ui_state, AppConfig, AppState, AppStateProvider, AppStateSummary, AuthState,
    ContentCacheStats, ContentLoaderProvider, LanguageContext, LanguageProvider, MetaState,
    Notification, NotificationLevel, ReactiveContentLoader, RouteState, SocialMeta, ThemeState,
    UIState, UserInfo,
};
pub use theme::{
    EffectiveTheme, ThemeConfig as ThemeConfiguration, ThemeMode, ThemeTransition, ThemeUtils,
};

/// Design system loading shortcut
pub fn load_design_system() -> Result<defs::DesignSystemConfig, Box<dyn std::error::Error>> {
    let config = crate::config::ContentManageConfig::from_env();
    let design_system_path = config.design_system_path();

    // Try to read from filesystem first
    match std::fs::read_to_string(&design_system_path) {
        Ok(content) => toml::from_str(&content).map_err(|e| {
            format!(
                "Failed to parse design system TOML at '{}': {e}",
                design_system_path.display()
            )
            .into()
        }),
        Err(e) => {
            #[cfg(target_arch = "wasm32")]
            {
                // WASM cannot access filesystem - use default configuration
                tracing::warn!(
                    "Design system file not accessible in WASM, using default configuration. {}",
                    e
                );
                Ok(defs::DesignSystemConfig::default())
            }
            #[cfg(not(target_arch = "wasm32"))]
            {
                // On native platforms, configuration files should exist
                panic!(
                    "Design system configuration file not found at '{}'. Create the file or set \
                     CONTENT_ROOT environment variable to point to the correct content \
                     directory.Error: {}",
                    design_system_path.display(),
                    e
                );
            }
        }
    }
}

/// Helper function to get configured content paths
pub fn get_configured_content_path(content_type: &str, lang: &str) -> String {
    let config = crate::config::ContentManageConfig::from_env();
    config
        .root_path
        .join(content_type)
        .join(lang)
        .to_string_lossy()
        .to_string()
}

/// Environment-aware path resolution
pub fn resolve_path(env_var: &str, default_path: &str) -> String {
    std::env::var(env_var).unwrap_or_else(|_| default_path.to_string())
}

/// Quick access to menu loading with fallback
pub fn load_menu_for_language(lang: &str) -> Result<defs::MenuConfig, Box<dyn std::error::Error>> {
    resources::load::menu(lang).map_err(|e| Box::new(e) as Box<dyn std::error::Error>)
}

/// Reactive menu loading function that provides consistent menu structure
/// across languages
pub fn load_reactive_menu_for_language(
    lang: &str,
) -> Result<Vec<defs::MenuItem>, Box<dyn std::error::Error>> {
    let menu_config = load_menu_for_language(lang)?;
    Ok(menu_config.menu)
}

/// Fallback menu loading function for backward compatibility
pub fn load_menu_toml() -> Result<defs::MenuConfig, Box<dyn std::error::Error>> {
    let default_language = i18n::discovery::get_default_language();
    load_menu_for_language(default_language)
}

/// Load menus for all available languages
///
/// This function discovers all configured languages and loads their menus
/// in a single operation. Useful for SSR context initialization.
///
/// # Returns
/// * `Result<HashMap<String, Vec<MenuItem>>, Box<dyn std::error::Error>>`
/// * `Ok(registry)` with all language menus loaded as HashMap
/// * `Err(e)` if loading fails for any language
///
/// # Usage
/// ```ignore
/// let menu_map = load_all_menus()?;
/// let mut registry = MenuRegistry::new();
/// for (lang, items) in menu_map {
///     registry.insert(lang, items);
/// }
/// provide_context(registry);
/// ```
pub fn load_all_menus(
) -> Result<std::collections::HashMap<String, Vec<MenuItem>>, Box<dyn std::error::Error>> {
    let mut registry = std::collections::HashMap::new();

    // Get all supported languages
    let languages = i18n::discover_available_languages();

    // Load menu for each language
    for lang in languages {
        match load_reactive_menu_for_language(lang) {
            Ok(menu_items) => {
                registry.insert(lang.clone(), menu_items);
            }
            Err(e) => {
                // Log warning but continue with other languages
                tracing::warn!("Failed to load menu for language '{}': {}", lang, e);
                // Insert empty menu as fallback to prevent rendering errors
                registry.insert(lang.clone(), vec![]);
            }
        }
    }

    Ok(registry)
}

/// Quick access to footer loading with fallback
pub fn load_footer_for_language(
    lang: &str,
) -> Result<defs::FooterConfig, Box<dyn std::error::Error>> {
    resources::load::footer(lang).map_err(|e| Box::new(e) as Box<dyn std::error::Error>)
}

/// Reactive footer loading function that provides consistent menu structure
/// across languages
pub fn load_reactive_footer_for_language(
    lang: &str,
) -> Result<defs::FooterConfig, Box<dyn std::error::Error>> {
    let footer_config = load_footer_for_language(lang)?;
    Ok(footer_config)
}

/// Quick access to theme loading with fallback
pub fn load_theme(name: &str) -> Result<ThemeConfig, Box<dyn std::error::Error>> {
    // Use trait type directly - no conversion needed in new architecture
    resources::load::theme(name).map_err(|e| Box::new(e) as Box<dyn std::error::Error>)
}

// /// Helper function to get configured content paths
// pub fn get_configured_content_path(content_type: &str, lang: &str) -> String
// {     let config = crate::config::ContentManageConfig::from_env();
//     config
//         .root_path
//         .join(content_type)
//         .join(lang)
//         .to_string_lossy()
//         .to_string()
// }

// /// Environment-aware path resolution
// pub fn resolve_path(env_var: &str, default_path: &str) -> String {
//     std::env::var(env_var).unwrap_or_else(|_| default_path.to_string())
// }

/// get Debug Value from rustelo manifest build.debug
/// 0 or less no debug output info
/// 1 main debug output info
/// 2 complementary debug output info
/// > 2 FOLLOW routes lookups and rendering
/// > 3 TRACE routes lookups and rendering
/// > 4 DEEP trace routes lookups and rendering
pub fn get_debug_value() -> i8 {
    rustelo_utils::get_debug_level() as i8
}
