use crate::config::AppConfig;
use stakpak_api::{AgentClient, AgentClientConfig, AgentProvider, StakpakConfig};
use tokio::time::Duration;
const MAX_RETRIES: u32 = 2;
pub async fn validate_profile_switch(
new_profile: &str,
config_path: Option<&str>,
default_api_key: Option<String>,
) -> Result<AppConfig, String> {
let mut new_config = AppConfig::load(new_profile, config_path)
.map_err(|e| format!("Failed to load profile '{}': {}", new_profile, e))?;
if new_config.api_key.is_none()
&& let Some(default_key) = default_api_key
{
new_config.api_key = Some(default_key);
}
let client: Box<dyn AgentProvider> = {
let stakpak = new_config
.get_stakpak_api_key()
.map(|api_key| StakpakConfig {
api_key,
api_endpoint: new_config.api_endpoint.clone(),
});
let client = AgentClient::new(AgentClientConfig {
stakpak,
providers: new_config.get_llm_provider_config(),
eco_model: new_config.eco_model.clone(),
recovery_model: new_config.recovery_model.clone(),
smart_model: new_config.smart_model.clone(),
store_path: None,
hook_registry: None,
})
.await
.map_err(|e| format!("Failed to create agent client: {}", e))?;
Box::new(client)
};
let mut last_error = String::new();
for attempt in 1..=MAX_RETRIES {
match client.get_my_account().await {
Ok(_) => {
return Ok(new_config);
}
Err(e) => {
last_error = e;
if attempt < MAX_RETRIES {
tokio::time::sleep(Duration::from_secs(attempt as u64)).await;
}
}
}
}
Err(format!(
"API validation failed after {} attempts: {}",
MAX_RETRIES, last_error
))
}