//! # 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::{fragment_with_path, shell_with_path};
use rustelo_server::rendering::RenderingProfile;
use rustelo_server::run::SiteOptions;

/// V2 shell renderer — profile-aware, registered via `register_shell_renderer_v2`.
///
/// Receives the resolved `RenderingProfile` and htmx extension list from the
/// framework dispatcher so the shell can emit the correct scripts for each mode.
pub fn render_shell_v2(
    site_options: SiteOptions,
    path: Option<String>,
    profile: RenderingProfile,
    htmx_extensions: Vec<String>,
) -> String {
    shell_with_path(site_options, path, profile, htmx_extensions)
}

/// Fragment renderer — returns just `<main>` for non-boosted HTMX requests.
///
/// Registered via `register_fragment_renderer`. The framework calls this when
/// `HX-Request: true` and `HX-Boosted` is absent/false.
pub fn render_fragment(
    _site_options: SiteOptions,
    resolution: &rustelo_core_lib::routing::engine::RouteResolution,
) -> String {
    fragment_with_path(&resolution.path, &resolution.language)
}

/// Legacy v1 compat — delegates to `render_shell_v2` with workspace profile.
pub fn render_ssr_with_context(site_options: SiteOptions, path: Option<String>) -> String {
    use rustelo_server::rendering::workspace_rendering_config;
    let cfg = workspace_rendering_config();
    render_shell_v2(
        site_options,
        path,
        cfg.default_profile,
        cfg.htmx_extensions.clone(),
    )
}

/// Render SSR using routing engine's resolution (profile taken from resolution).
pub fn render_ssr_with_route_resolution(
    site_options: SiteOptions,
    resolution: &rustelo_core_lib::routing::engine::RouteResolution,
) -> String {
    use rustelo_server::rendering::workspace_rendering_config;
    let cfg = workspace_rendering_config();
    tracing::info!(
        "render_ssr_with_route_resolution path='{}' profile={}",
        resolution.path,
        resolution.rendering_profile
    );
    render_shell_v2(
        site_options,
        Some(resolution.path.clone()),
        resolution.rendering_profile,
        cfg.htmx_extensions.clone(),
    )
}

/// Run the Axum server - simplified version using rustelo_server directly
pub async fn run_server() -> Result<(), Box<dyn std::error::Error>> {
    // Use the rustelo_server run_server function directly
    // This provides all the functionality but through rustelo_server
    rustelo_server::run::run_server().await
}

/// Main entry point for the Axum/Leptos server.
///
/// Uses `tokio::runtime::LocalRuntime` (tokio_unstable) so that `spawn_local`
/// is valid from *any* task context — including connection tasks that
/// `axum::serve` spawns internally via `tokio::spawn`.
///
/// The previous `current_thread + LocalSet::run_until` pattern broke because
/// `LocalSet` only activates its local context while *its own* future is being
/// polled; tasks spawned by `tokio::spawn` inside `axum::serve` escape that
/// scope and call `spawn_local` → panic.  `LocalRuntime` makes the entire
/// runtime "local", eliminating the scope gap.
pub fn run_main() -> Result<(), Box<dyn std::error::Error>> {
    rustelo_server::utils::init();

    rustelo_server::utils::paths::set_migrations_dir(crate::config_constants::SITE_MIGRATIONS_PATH);
    rustelo_server::utils::paths::set_email_templates_dir(
        crate::config_constants::SITE_EMAIL_TEMPLATES_PATH,
    );

    crate::resources::initialize()?;

    // Linker-safe explicit registration of every server function. The
    // inventory-based auto-registration is unreliable in release/container
    // builds; this loop guarantees `handle_server_fns` resolves every
    // `POST /api/<fn><hash>` route.
    #[cfg(feature = "wasm-client")]
    crate::server_fn_register::register_all();

    let rt = tokio::runtime::LocalRuntime::new()?;
    rt.block_on(run_server())
}
