use anyhow::Result;
use tracing::info;
use tracing_subscriber::EnvFilter;
use std::sync::Arc;
use workflow_orchestrator_service::{config, state, message_consumer, api};

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

    info!("Starting workflow-orchestrator-service...");

    // Load configuration
    let config = config::AppConfig::load()?;
    
    // Initialize application state
    let state = Arc::new(state::AppState::new(config.clone()).await?);

    // Connect to NATS
    let nats_client = async_nats::connect(&config.nats_addr).await?;
    info!("Connected to NATS at {}", config.nats_addr);

    // Start Message Consumer
    let state_clone = state.clone();
    let nats_clone = nats_client.clone();
    tokio::spawn(async move {
        if let Err(e) = message_consumer::run(state_clone, nats_clone).await {
             tracing::error!("Message consumer failed: {}", e);
        }
    });

    // Start HTTP Server
    let app = api::create_router(state.clone());
    let addr = format!("0.0.0.0:{}", config.server_port);
    let listener = tokio::net::TcpListener::bind(&addr).await?;
    info!("HTTP server listening on {}", addr);
    
    axum::serve(listener, app).await?;

    Ok(())
}
