use std::fs;
use std::path::{Path, PathBuf};

use lobe_core::error::Result;
use lobe_core::storage::SqliteStore;

pub fn open_store(path: Option<&Path>) -> Result<SqliteStore> {
    let db_path = match path {
        Some(path) => path.to_path_buf(),
        None => default_db_path(),
    };

    if let Some(parent) = db_path.parent() {
        fs::create_dir_all(parent)?;
    }

    SqliteStore::open(db_path)
}

fn default_db_path() -> PathBuf {
    let base_dir = std::env::var_os("HOME")
        .or_else(|| std::env::var_os("USERPROFILE"))
        .map(PathBuf::from)
        .unwrap_or_else(|| PathBuf::from("."));

    base_dir.join(".lobe").join("history.db")
}
