use std::sync::Arc;

use crate::agent::AgentError;
use crate::storage::SessionStore;

use super::memory_maintenance::{
    MemoryMaintenanceScopeResult, MemoryMaintenanceService, MemoryOrganizationOutput,
};
use super::provider_config_service::ProviderConfigService;

#[derive(Clone)]
pub(crate) struct MemoryMaintenanceCoordinator {
    store: Arc<SessionStore>,
    provider_configs: ProviderConfigService,
}

impl MemoryMaintenanceCoordinator {
    pub(crate) fn new(store: Arc<SessionStore>, provider_configs: ProviderConfigService) -> Self {
        Self {
            store,
            provider_configs,
        }
    }

    #[cfg_attr(not(test), allow(dead_code))]
    pub(crate) async fn organize_for_scope(
        &self,
        scope_key: &str,
    ) -> Result<Option<MemoryOrganizationOutput>, AgentError> {
        self.service()?.organize_for_scope(scope_key).await
    }

    pub(crate) async fn run_for_all_scopes(
        &self,
    ) -> Result<Option<MemoryMaintenanceScopeResult>, AgentError> {
        self.service()?.run_for_all_scopes().await
    }

    fn service(&self) -> Result<MemoryMaintenanceService, AgentError> {
        Ok(MemoryMaintenanceService::new(
            self.store.clone(),
            self.provider_configs.default_provider_config(),
            self.provider_configs.default_maintenance_config(),
        ))
    }
}
