mod api;
mod config;
mod error;
mod llm_client;
mod message_consumer;
mod persistence;
mod state;
mod templates;
mod worker;

use crate::config::AppConfig;
use crate::error::{ProviderError, Result};
use crate::state::AppState;
use tracing::info;

#[tokio::main]
async fn main() -> Result<()> {
    // Initialize logging
    tracing_subscriber::fmt()
        .with_env_filter(tracing_subscriber::EnvFilter::from_default_env())
        .init();

    info!("Starting report-generator-service...");

    // Load configuration
    let config = AppConfig::load().map_err(|e| ProviderError::Configuration(e.to_string()))?;
    let port = config.server_port;

    // Initialize application state
    let app_state = AppState::new(config);

    // Create the Axum router
    let app = api::create_router(app_state.clone());

    // --- Start the message consumer ---
    let nats_client = async_nats::connect(app_state.config.nats_addr.clone())
        .await
        .map_err(|e| ProviderError::Internal(anyhow::anyhow!(e.to_string())))?;
    let state_clone = app_state.clone();
    tokio::spawn(async move {
        if let Err(e) = message_consumer::subscribe_to_commands(state_clone, nats_client).await {
            tracing::error!("message consumer exited with error: {:?}", e);
        }
    });

    // Start the HTTP server
    let listener = tokio::net::TcpListener::bind(format!("0.0.0.0:{}", port))
        .await
        .unwrap();
    info!("HTTP server listening on port {}", port);
    axum::serve(listener, app).await.unwrap();

    Ok(())
}
