//! # RUSTELO Server Binary
//!
//! <div align="center">
//!   <img src="../logos/rustelo_dev-logo-h.svg" alt="RUSTELO" width="300" />
//! </div>
//!
//! Main server executable for the RUSTELO web application framework.
//!
//! ## Overview
//!
//! This is the main entry point for the RUSTELO server application. It initializes all services,
//! sets up routing, configures middleware, and starts the web server with support for:
//!
//! - **Authentication & Authorization** - JWT tokens, OAuth2, 2FA, RBAC
//! - **Content Management** - Markdown processing, media handling, database storage
//! - **Email Services** - Multi-provider email with templating
//! - **Security** - CSRF protection, rate limiting, HTTPS/TLS
//! - **Performance** - Metrics collection, connection pooling, caching
//!
//! ## Features
//!
//! ### Core Features (Always Available)
//! - **HTTP Server** - Fast Axum-based web server
//! - **Static Files** - Efficient static file serving
//! - **Health Checks** - Server health monitoring
//! - **CSRF Protection** - Cross-site request forgery protection
//! - **Rate Limiting** - Request rate limiting and throttling
//! - **Security Headers** - Comprehensive security headers
//!
//! ### Optional Features (Feature-Gated)
//! - **`auth`** - Complete authentication system with JWT, OAuth2, 2FA
//! - **`content-db`** - Database-backed content management
//! - **`email`** - Email sending with multiple providers
//! - **`tls`** - HTTPS/TLS encryption support
//! - **`metrics`** - Performance monitoring and metrics collection
//!
//! ## Usage
//!
//! ```bash
//! # Start with default configuration
//! cargo run
//!
//! # Start with specific features
//! cargo run --features "auth,content-db,email,tls"
//!
//! # Start with custom configuration
//! RUSTELO_CONFIG=custom.toml cargo run
//! ```
//!
//! ## Configuration
//!
//! The server can be configured through:
//! - Environment variables (prefixed with `RUSTELO_`)
//! - TOML configuration files
//! - Command-line arguments
//! - Default values with sensible fallbacks
//!
//! ### Example Configuration
//!
//! ```toml
//! [server]
//! host = "127.0.0.1"
//! port = 3030
//! protocol = "https"
//!
//! [database]
//! url = "postgresql://user:pass@localhost/rustelo"
//! max_connections = 10
//!
//! [auth]
//! jwt_secret = "your-secret-key"
//! jwt_expiration_hours = 24
//! enable_2fa = true
//!
//! [email]
//! provider = "smtp"
//! from_address = "noreply@rustelo.dev"
//! ```
//!
//! ## Architecture
//!
//! The server follows a modular architecture with clear separation of concerns:
//!
//! ### Application State
//! - **Leptos Integration** - SSR options and hydration
//! - **Security Services** - CSRF protection and rate limiting
//! - **Authentication** - JWT service and user management
//! - **Content Services** - Content processing and storage
//! - **Email Services** - Email templating and delivery
//! - **Metrics** - Performance monitoring and collection
//!
//! ### Request Handling
//! - **Routing** - API endpoints and static file serving
//! - **Middleware** - Authentication, CORS, security headers
//! - **Error Handling** - Comprehensive error responses
//! - **Logging** - Structured logging with tracing
//!
//! ## Security
//!
//! The server implements multiple security layers:
//!
//! - **Memory Safety** - Rust's ownership system prevents vulnerabilities
//! - **Input Validation** - Comprehensive validation of all inputs
//! - **CSRF Protection** - Token-based CSRF protection
//! - **Rate Limiting** - Request throttling and abuse prevention
//! - **Security Headers** - HSTS, CSP, X-Frame-Options, etc.
//! - **TLS/HTTPS** - End-to-end encryption (when enabled)
//!
//! ## Performance
//!
//! Optimized for high performance:
//!
//! - **Async/Await** - Non-blocking I/O with Tokio
//! - **Connection Pooling** - Efficient database connections
//! - **Static File Caching** - Optimized static asset serving
//! - **Request Deduplication** - Efficient request handling
//! - **Metrics Collection** - Performance monitoring and optimization
//!
//! ## Monitoring
//!
//! Built-in monitoring capabilities:
//!
//! - **Health Endpoints** - `/health` for service monitoring
//! - **Metrics Collection** - Prometheus-compatible metrics
//! - **Structured Logging** - JSON-formatted logs for analysis
//! - **Error Tracking** - Comprehensive error reporting
//!
//! ## License
//!
//! This project is licensed under the MIT License - see the [LICENSE](https://github.com/yourusername/rustelo/blob/main/LICENSE) file for details.

// #![allow(unused_variables)]
// #![recursion_limit = "512"]

use crate::shell::shell_with_path;

/// Helper function to render SSR with proper reactive context
pub fn render_ssr_with_context(leptos_options: LeptosOptions, path: Option<String>) -> String {
    use leptos::prelude::*;

    // Create a proper reactive context for SSR rendering
    let owner = Owner::new();
    owner.with(|| shell_with_path(leptos_options, path).to_html())
}

/// Helper function to render SSR using routing engine's resolution
pub fn render_ssr_with_route_resolution(
    leptos_options: LeptosOptions,
    resolution: &rustelo_core_lib::routing::engine::RouteResolution,
) -> String {
    // Use the resolved path directly from the routing engine
    // The routing engine has already determined the correct path based on TOML configuration
    let path = resolution.path.clone();

    tracing::info!(
        "🔧 render_ssr_with_route_resolution using resolved path: '{}'",
        path
    );

    // Use the existing shell function with the resolved path
    // This ensures header, footer, and layout are included
    shell_with_path(leptos_options, Some(path)).to_html()
}

// Moved CSRF and RateLimiter imports to app_state module
#[cfg(feature = "auth")]
use auth::{
    auth_middleware, create_auth_routes, AuthService, JwtService, OAuthService, PasswordService,
    TwoFactorService,
};
#[cfg(feature = "content-db")]
use content::{create_content_routes, ContentRepository, ContentService, ContentSource};
#[cfg(any(feature = "auth", feature = "content-db"))]
use database::{Database, DatabaseConfig, DatabasePool};
#[cfg(feature = "email")]
use email::{EmailService, EmailServiceBuilder};
#[cfg(feature = "email")]
use handlers::email::create_email_routes;
use leptos::prelude::*;
#[cfg(feature = "metrics")]
use metrics::{create_metrics_routes, metrics_middleware, MetricsService};
#[cfg(any(feature = "auth", feature = "content-db"))]
use std::sync::Arc;
#[cfg(feature = "auth")]
use tower_cookies::CookieManagerLayer;

// Import AppState from the dedicated app_state module
use crate::app_state::AppState;

/// Run the Axum server with all features and routes properly configured
///
/// This refactored function uses modular startup functions for better maintainability.
/// Each aspect of server initialization is handled by focused, single-responsibility functions
/// located in the startup module.
pub async fn run_server() -> Result<(), Box<dyn std::error::Error>> {
    use crate::startup::*;

    // 1. Environment setup
    setup_environment().await?;

    // 2. Load and validate configuration
    let config = load_and_validate_config().await?;

    // 3. Setup logging and panic handling
    setup_logging_and_panic_handling(&config)?;

    // 4. Initialize navigation tracking system
    initialize_navigation_tracking(&config)?;

    // 4. Initialize meta configuration preloader for SSR (after logging is set up)
    rustelo_core_lib::init_meta_preloader();

    // 5. Initialize cache system
    let (_cache_dir, _shared_cache_config, content_cache) =
        initialize_cache_system(&config).await?;

    // 6. Setup Leptos configuration
    let leptos_options = setup_leptos_config(&config)?;

    // 7. Initialize security components
    let (csrf_state, rate_limiter, security_headers_config) =
        initialize_security_components(&config);

    // 8. Initialize database if needed
    #[cfg(any(feature = "auth", feature = "content-db"))]
    let (database, pool, database_pool) = initialize_database(&config).await?;

    // 9. Initialize services based on enabled features
    #[cfg(feature = "auth")]
    let (auth_service, auth_repository, jwt_service) =
        initialize_auth_services(&database_pool, &config).await?;

    #[cfg(feature = "content-db")]
    let content_service = initialize_content_services(&database_pool);

    #[cfg(feature = "email")]
    let email_service = initialize_email_service(&config).await?;

    #[cfg(feature = "metrics")]
    let metrics_result = initialize_metrics_service(&config)?;
    #[cfg(feature = "metrics")]
    let metrics_registry = metrics_result
        .as_ref()
        .map(|(_, registry)| registry.clone())
        .flatten();

    // 10. Create application state
    let app_state = AppState {
        leptos_options: leptos_options.clone(),
        csrf_state,
        rate_limiter,
        #[cfg(feature = "auth")]
        auth_service: auth_service.clone(),
        #[cfg(feature = "auth")]
        jwt_service: jwt_service.clone(),
        #[cfg(feature = "auth")]
        auth_repository: auth_repository.clone(),
        #[cfg(feature = "content-db")]
        content_service: content_service.clone(),
        #[cfg(feature = "email")]
        email_service: email_service.clone(),
        #[cfg(feature = "metrics")]
        metrics_registry,
    };

    // 11. Create main application router
    let main_app = create_main_router(&config, leptos_options.clone(), app_state.clone())?;

    // 12. Create API router with all service routes
    let api_router = create_api_router(
        &config,
        &app_state,
        content_cache.clone(),
        #[cfg(feature = "auth")]
        auth_service.clone(),
        #[cfg(feature = "content-db")]
        content_service.clone(),
        #[cfg(feature = "email")]
        email_service.clone(),
    )?;

    // 13. Combine routers
    let app_with_api = main_app.nest("/api", api_router);

    // 14. Apply all middleware layers
    let final_app = apply_middleware_layers(
        app_with_api,
        &config,
        &app_state,
        security_headers_config,
        #[cfg(feature = "auth")]
        jwt_service.clone(),
        #[cfg(feature = "auth")]
        auth_repository.clone(),
    );

    // 15. Start the server
    start_server(final_app, &config).await?;

    Ok(())
}

/// Main entry point for the Axum/Leptos server.
///
/// Uses current_thread runtime with LocalSet to provide the proper runtime context for Leptos.
/// This fixes the "spawn_local called from outside of a task::LocalSet" error.
pub fn run_main() -> Result<(), Box<dyn std::error::Error>> {
    // Initialize path utilities first
    crate::utils::init();

    // Create a current_thread runtime which is compatible with LocalSet
    let rt = tokio::runtime::Builder::new_current_thread()
        .enable_all()
        .build()?;

    // Create a LocalSet and run everything within it
    let local = tokio::task::LocalSet::new();

    rt.block_on(local.run_until(async { run_server().await }))
}
