use crate::error::Result;
use crate::state::AppState;
use common_contracts::config_models::{DataSourceConfig, DataSourceProvider};
use std::collections::HashMap;
use std::time::Duration;
use tracing::{error, info, instrument};

const POLLING_INTERVAL_SECONDS: u64 = 60;

#[instrument(skip(state))]
pub async fn run_config_poller(state: AppState) {
    info!("Starting configuration poller...");
    let mut interval = tokio::time::interval(Duration::from_secs(POLLING_INTERVAL_SECONDS));
    interval.tick().await; // Initial tick happens immediately

    loop {
        if let Err(e) = poll_and_update_config(&state).await {
            error!("Failed to poll and update config: {:?}", e);
        }
        interval.tick().await;
    }
}

async fn poll_and_update_config(state: &AppState) -> Result<()> {
    info!("Polling for data source configurations...");
    let client = reqwest::Client::new();
    let url = format!(
        "{}/api/v1/configs/data_sources",
        state.config.data_persistence_service_url
    );

    let response = client.get(&url).send().await?;
    response.error_for_status_ref()?;

    let configs: HashMap<String, DataSourceConfig> = response.json().await?;

    let tushare_config = configs.values().find(|cfg| {
        matches!(cfg.provider, DataSourceProvider::Tushare) && cfg.enabled
    });

    if let Some(config) = tushare_config {
        if let Some(api_key) = &config.api_key {
            state.update_provider(
                Some(api_key.clone().into()), 
                config.api_url.clone()
            ).await;
            info!("Successfully updated Tushare provider with new configuration.");
        } else {
            state.update_provider(None, None).await;
            info!("Tushare provider is enabled but API key is missing. Service is degraded.");
        }
    } else {
        state.update_provider(None, None).await;
        info!("No enabled Tushare configuration found. Service is degraded.");
    }

    Ok(())
}
