use anyhow::{Context, Result};
use directories::ProjectDirs;
use serde::{Deserialize, Serialize};
use std::fs;
use std::path::PathBuf;
const ENV_KEY: &str = "OPENROUTER_API_KEY";
#[derive(Debug, Default, Serialize, Deserialize)]
struct Config {
api_key: Option<String>,
}
fn config_path() -> Result<PathBuf> {
let dirs =
ProjectDirs::from("ai", "lmocr", "lmocr").context("Failed to resolve config directory")?;
Ok(dirs.config_dir().join("config.toml"))
}
pub fn save_api_key(key: &str) -> Result<()> {
let path = config_path()?;
if let Some(parent) = path.parent() {
fs::create_dir_all(parent)?;
}
let cfg = Config {
api_key: Some(key.to_string()),
};
let text = toml::to_string_pretty(&cfg)?;
fs::write(path, text)?;
Ok(())
}
pub fn get_api_key() -> Result<String> {
if let Ok(val) = std::env::var(ENV_KEY)
&& !val.trim().is_empty()
{
return Ok(val);
}
let path = config_path()?;
let contents =
fs::read_to_string(&path).with_context(|| format!("Missing config at {:?}", path))?;
let cfg: Config = toml::from_str(&contents)?;
cfg.api_key
.filter(|k| !k.trim().is_empty())
.context("OpenRouter API key not set. Run `lmocr auth <key>`.")
}