mod api;
mod config;
mod error;
mod mapping;
mod message_consumer;
mod persistence;
mod state;
mod ts_client;
mod tushare;
mod worker;
mod config_poller;

use crate::config::AppConfig;
use crate::error::{Result, AppError};
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 tushare-provider-service...");

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

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

    // --- Start the config poller ---
    tokio::spawn(config_poller::run_config_poller(app_state.clone()));

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

    // --- Start the message consumer ---
    tokio::spawn(message_consumer::run(app_state));

    // 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(())
}
