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;
use common_contracts::lifecycle::ServiceRegistrar;
use common_contracts::registry::{ServiceRegistration, ServiceRole};
use std::sync::Arc;

#[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;

    // --- Connect to NATS ---
    let nats_client = async_nats::connect(config.nats_addr.clone())
        .await
        .map_err(|e| ProviderError::Internal(anyhow::anyhow!(e.to_string())))?;

    // Initialize application state
    let app_state = AppState::new(config.clone(), nats_client.clone());

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

    // --- Start the message consumer ---
    let state_clone = app_state.clone();
    let nats_clone = nats_client.clone();
    tokio::spawn(async move {
        if let Err(e) = message_consumer::subscribe_to_commands(state_clone, nats_clone).await {
            tracing::error!("message consumer exited with error: {:?}", e);
        }
    });

    // --- Service Registration ---
    // Report Generator needs to know API Gateway URL to register.
    // Since AppConfig doesn't have it yet, we'll assume standard docker-compose naming or read env var directly.
    let gateway_url = std::env::var("API_GATEWAY_URL").unwrap_or_else(|_| "http://api-gateway:4000".to_string());
    let service_host = std::env::var("SERVICE_HOST").unwrap_or_else(|_| "report-generator-service".to_string());

    let registrar = ServiceRegistrar::new(
        gateway_url,
        ServiceRegistration {
            service_id: format!("{}-{}", "report-generator", uuid::Uuid::new_v4()),
            service_name: "report-generator".to_string(),
            role: ServiceRole::ReportGenerator,
            base_url: format!("http://{}:{}", service_host, port),
            health_check_url: format!("http://{}:{}/health", service_host, port),
            metadata: None,
        }
    );
    
    // Initial registration attempt (best effort)
    let _ = registrar.register().await;

    // Start heartbeat loop
    let registrar = Arc::new(registrar);
    tokio::spawn(registrar.clone().start_heartbeat_loop());

    // 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)
        .with_graceful_shutdown(shutdown_signal(registrar))
        .await
        .unwrap();

    Ok(())
}

async fn shutdown_signal(registrar: Arc<ServiceRegistrar>) {
    let ctrl_c = async {
        tokio::signal::ctrl_c()
            .await
            .expect("failed to install Ctrl+C handler");
    };

    #[cfg(unix)]
    let terminate = async {
        tokio::signal::unix::signal(tokio::signal::unix::SignalKind::terminate())
            .expect("failed to install signal handler")
            .recv()
            .await;
    };

    #[cfg(not(unix))]
    let terminate = std::future::pending::<()>();

    tokio::select! {
        _ = ctrl_c => {},
        _ = terminate => {},
    }

    info!("Shutdown signal received, deregistering service...");
    let _ = registrar.deregister().await;
}