use std::path::{Path, PathBuf};
use anyhow::{Context, bail};
use rusqlite::Connection;
use crate::config::UblxPaths;
use crate::engine::db_ops::{
SnapshotReaderPreference, open_for_snapshot_tui_read, snapshot_reader_path_with,
};
use crate::utils;
#[derive(Debug, Clone)]
pub struct CatalogPaths {
pub dir: PathBuf,
pub paths: UblxPaths,
pub db_path: PathBuf,
}
pub struct CatalogHandle {
pub paths: CatalogPaths,
pub read_path: PathBuf,
pub conn: Connection,
}
pub fn resolve_catalog_dir(dir: &Path) -> Result<PathBuf, String> {
utils::try_validate_dir(dir)
}
pub fn resolve_catalog_paths(dir: &Path) -> Result<CatalogPaths, anyhow::Error> {
let dir = resolve_catalog_dir(dir).map_err(|e| anyhow::anyhow!("{e}"))?;
let paths = UblxPaths::new(&dir);
let db_path = paths.db();
Ok(CatalogPaths {
dir,
paths,
db_path,
})
}
pub fn open_catalog_for_read(dir: &Path) -> Result<CatalogHandle, anyhow::Error> {
let catalog_paths = resolve_catalog_paths(dir)?;
let Some(read_path) =
snapshot_reader_path_with(&catalog_paths.db_path, SnapshotReaderPreference::PreferUblx)
else {
bail!(
"no catalog DB for {} (expected {}); run `ublx` or `ublx -s` in that directory first",
catalog_paths.dir.display(),
catalog_paths.db_path.display()
);
};
let conn = open_for_snapshot_tui_read(&read_path)
.with_context(|| format!("failed to open catalog {}", read_path.display()))?;
Ok(CatalogHandle {
paths: catalog_paths,
read_path,
conn,
})
}
#[must_use]
pub fn snapshot_likely_in_progress(catalog_paths: &CatalogPaths) -> bool {
let p = &catalog_paths.paths;
p.tmp().exists() && (p.tmp_wal().exists() || p.tmp_shm().exists())
}