//! Global state and public API for the routing engine
//!
//! This module provides the global singleton instance and public functions
//! for accessing routing functionality throughout the application.

use std::sync::{Mutex, OnceLock};

use rustelo_language::get_language_registry;

use super::types::{NavigationItem, RouteMetadata, RouteResolution};
use super::RoutingEngine;
use crate::components::{RouteComponent, RouteConfigToml};
use crate::config::get_routing_config;
use crate::utils::{
    generate_sitemap_data, get_breadcrumbs, get_localized_route, BreadcrumbItem, SitemapEntry,
};

/// Global routing engine instance (thread-safe)
static ROUTING_ENGINE: OnceLock<Mutex<RoutingEngine>> = OnceLock::new();

/// Get the global routing engine instance
pub fn get_routing_engine() -> &'static Mutex<RoutingEngine> {
    ROUTING_ENGINE.get_or_init(|| Mutex::new(RoutingEngine::new()))
}

/// Get mutable routing engine for navigation cache updates
pub fn get_routing_engine_mut() -> &'static Mutex<RoutingEngine> {
    get_routing_engine()
}

/// Resolve a route using the unified TOML system
pub fn resolve_route(path: &str) -> RouteResolution {
    get_routing_engine()
        .lock()
        .map(|engine| engine.resolve_unified_route(path))
        .unwrap_or_else(|_| {
            let default_language = get_language_registry().get_default_language();
            RouteResolution {
                path: path.to_string(),
                language: default_language.to_string(),
                component: Some(RouteComponent::NOT_FOUND),
                canonical_path: path.to_string(),
                metadata: RouteMetadata::default(),
                exists: false,
                parameters: std::collections::HashMap::new(),
                rendering_profile: rustelo_core_types::rendering::resolve_rendering_profile(None),
                template: None,
            }
        })
}

/// Get unified route with full metadata
pub fn resolve_unified_route(path: &str) -> RouteResolution {
    resolve_route(path)
}

/// Check if a route is valid using TOML configuration
pub fn is_valid_route(path: &str) -> bool {
    get_routing_engine()
        .lock()
        .map(|engine| engine.route_exists(path))
        .unwrap_or(false)
}

/// Get menu navigation for a language
pub fn get_menu_navigation(language: &str) -> Vec<NavigationItem> {
    get_routing_engine_mut()
        .lock()
        .map(|mut engine| engine.get_navigation_items(language))
        .unwrap_or_else(|_| Vec::new())
}

/// Get language switch URL for current path
pub fn get_language_switch_url(current_path: &str, target_language: &str) -> String {
    get_localized_route(current_path, target_language)
}

/// Get breadcrumbs for a path
pub fn get_route_breadcrumbs(path: &str, base_url: &str) -> Vec<BreadcrumbItem> {
    get_breadcrumbs(path, base_url)
}

/// Get sitemap routes
pub fn get_sitemap_routes() -> Vec<SitemapEntry> {
    // Use the base URL from environment or default
    let base_url = std::env::var("BASE_URL").unwrap_or_else(|_| "https://example.com".to_string());
    generate_sitemap_data(&base_url)
}

/// Get TOML routes for a language
pub fn get_toml_routes_for_language(language: &str) -> Vec<&'static RouteConfigToml> {
    // Since we can't return borrowed references from a mutex lock,
    // we'll use the static config directly
    let config = get_routing_config();
    config
        .routes
        .iter()
        .filter(|route| route.enabled && route.language == language)
        .collect()
}
