use serde::{Deserialize, Serialize};
use std::{fs, path::PathBuf};
#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct Config {
pub api_endpoint: String,
pub model: String,
pub stream: bool,
pub temperature: f32,
}
impl Config {
pub fn load() -> Result<Self, FSError> {
let config_dir = dirs::home_dir()
.ok_or(FSError::HomeDirNotFound)?
.join(".config")
.join("chatti");
fs::create_dir_all(&config_dir).map_err(FSError::IoError)?;
let config_path = config_dir.join("config.toml");
if !config_path.exists() {
Self::create_default_config(&config_path)?;
}
let config_content = fs::read_to_string(&config_path).map_err(FSError::IoError)?;
let config: Config = toml::from_str(&config_content).map_err(FSError::TomlParseError)?;
Ok(config)
}
fn create_default_config(path: &PathBuf) -> Result<(), FSError> {
let default_config = Config {
api_endpoint: String::new(),
model: String::new(),
stream: false,
temperature: 0.7,
};
let toml_string = toml::to_string(&default_config).map_err(FSError::TomlSerializeError)?;
fs::write(path, toml_string).map_err(FSError::IoError)?;
Ok(())
}
}
#[derive(Debug, thiserror::Error)]
pub enum FSError {
#[error("home directory not found")]
HomeDirNotFound,
#[error("IO error: {0}")]
IoError(#[from] std::io::Error),
#[error("TOML parse error: {0}")]
TomlParseError(#[from] toml::de::Error),
#[error("Toml serialize error: {0}")]
TomlSerializeError(#[from] toml::ser::Error),
}