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>,
pub model: Option<String>,
}
const DEFAULT_MODEL: &str = "openai/gpt-oss-120b";
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)
}
pub fn get_model() -> Result<String, String> {
if let Ok(model) = env::var("OPENROUTER_MODEL") {
if !model.is_empty() {
return Ok(model);
}
}
let mut config = load_config()?;
if let Some(ref model) = config.model {
if !model.is_empty() {
return Ok(model.clone());
}
}
let prompt = format!("Enter OpenRouter model [{}]: ", DEFAULT_MODEL);
let input = ui::prompt_input(&prompt);
let model = if input.is_empty() {
DEFAULT_MODEL.to_string()
} else {
input
};
config.model = Some(model.clone());
save_config(&config)?;
let path = config_path().unwrap_or_default();
println!("Model saved to {}", path.display());
Ok(model)
}