use serde::{Deserialize, Serialize};
use std::env;
use std::fs;
use std::path::PathBuf;
use crate::ui;
#[derive(Debug, Default, Serialize, Deserialize)]
pub struct Config {
pub api_key: Option<String>,
}
fn config_path() -> Result<PathBuf, String> {
let home = dirs::home_dir()
.ok_or_else(|| "Could not determine home directory".to_string())?;
Ok(home.join(".config").join("quick-commit").join("config.toml"))
}
fn load_config() -> Result<Config, String> {
let path = config_path()?;
if !path.exists() {
return Ok(Config::default());
}
let contents =
fs::read_to_string(&path).map_err(|e| format!("Failed to read config: {}", e))?;
toml::from_str(&contents).map_err(|e| format!("Failed to parse config: {}", e))
}
fn save_config(config: &Config) -> Result<(), String> {
let path = config_path()?;
if let Some(parent) = path.parent() {
fs::create_dir_all(parent)
.map_err(|e| format!("Failed to create config directory: {}", e))?;
}
let contents =
toml::to_string_pretty(config).map_err(|e| format!("Failed to serialize config: {}", e))?;
fs::write(&path, contents).map_err(|e| format!("Failed to write config: {}", e))
}
pub fn get_api_key() -> Result<String, String> {
if let Ok(key) = env::var("OPENROUTER_API_KEY") {
if !key.is_empty() {
return Ok(key);
}
}
let mut config = load_config()?;
if let Some(ref key) = config.api_key {
if !key.is_empty() {
return Ok(key.clone());
}
}
let key = ui::prompt_input("Enter your OpenRouter API key: ");
if key.is_empty() {
return Err("No API key provided".to_string());
}
config.api_key = Some(key.clone());
save_config(&config)?;
let path = config_path().unwrap_or_default();
println!("API key saved to {}", path.display());
Ok(key)
}