//! jpl-website - Main Application Entry Point
//!
//! Generated by cargo rustelo v0.1.0 from content-website template
//! This is your main application server using the Rustelo framework.
//! Customize this file as needed - it won't be overwritten by framework updates.

use axum::{
    extract::State,
    response::{Html, IntoResponse},
    routing::get,
    Router,
};
use leptos::*;
use leptos_axum::{generate_route_list, LeptosRoutes};
use rustelo_core::config::RusteloConfig;
use tower_http::services::ServeDir;
use tracing_subscriber::{layer::SubscriberExt, util::SubscriberInitExt};

// Import your application components
use jpl_website::app::App;

#[derive(Clone)]
pub struct AppState {
    pub rustelo_config: RusteloConfig,
    // Add your application state here
}

#[tokio::main]
async fn main() -> anyhow::Result<()> {
    // Initialize logging
    tracing_subscriber::registry()
        .with(
            tracing_subscriber::EnvFilter::try_from_default_env()
                .unwrap_or_else(|_| "jpl_website=debug,tower_http=debug".into()),
        )
        .with(tracing_subscriber::fmt::layer())
        .init();

    tracing::info!("🚀 Starting jpl-website server...");
    tracing::info!("📦 Template: content-website");
    tracing::info!("🔧 Generated at: 2025-10-28T18:46:17.145459+00:00");

    // Load Rustelo framework configuration
    let rustelo_config = RusteloConfig::load().unwrap_or_default();

    // Create application state
    let app_state = AppState {
        rustelo_config: rustelo_config.clone(),
    };

    tracing::info!("📋 Loaded framework configuration");

    // Generate Leptos route list for SSR
    let routes = generate_route_list(App);

    // Build the application router
    let app = Router::new()
        // Leptos routes with SSR
        .leptos_routes(&app_state, routes, App)
        .route("/api/health", get(health_check))
        .route("/api/info", get(app_info))
        // Serve static assets
        .nest_service("/assets", ServeDir::new("assets"))
        .nest_service("/pkg", ServeDir::new("target/site/pkg"))
        .fallback_service(ServeDir::new("target/site"))
        .with_state(app_state);

    // Start the server
    let addr = rustelo_config.server.bind_address();
    tracing::info!("🌐 Server listening on http://{}", addr);
    tracing::info!("✨ jpl-website is ready!");

    let listener = tokio::net::TcpListener::bind(&addr).await?;
    axum::serve(listener, app).await?;

    Ok(())
}

/// Health check endpoint
async fn health_check() -> impl IntoResponse {
    axum::Json(serde_json::json!({
        "status": "healthy",
        "service": "jpl-website",
        "template": "content-website",
        "framework": "rustelo",
        "timestamp": chrono::Utc::now().to_rfc3339()
    }))
}

/// Application info endpoint
async fn app_info(State(state): State<AppState>) -> impl IntoResponse {
    axum::Json(serde_json::json!({
        "name": "jpl-website",
        "version": env!("CARGO_PKG_VERSION"),
        "description": env!("CARGO_PKG_DESCRIPTION"),
        "template": {
            "variant": "content-website",
            "generated_at": "2025-10-28T18:46:17.145459+00:00",
            "asset_source": "local"
        },
        "framework": {
            "name": "rustelo",
            "version": "0.1.0",
            "architecture": "framework-as-dependency"
        },
        "features": {
            "ssr": cfg!(feature = "ssr"),
            "auth": cfg!(feature = "auth"),
            "content": cfg!(feature = "content"),
            "database": cfg!(feature = "database")
        },
        "build": {
            "target": env!("TARGET"),
            "profile": if cfg!(debug_assertions) { "debug" } else { "release" },
            "rust_version": env!("RUSTC_VERSION")
        }
    }))
}
