use crate::config::IndexConfig;
use serde::{Deserialize, Serialize};
use sha2::{Digest, Sha256};
use std::path::{Path, PathBuf};
use synwire_storage::{StorageLayout, WorktreeId};
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct IndexMeta {
pub path: String,
pub indexed_at: String,
pub files_indexed: usize,
pub chunks_produced: usize,
pub version: u32,
}
#[must_use]
#[allow(dead_code)]
pub fn cache_dir_from_layout(layout: &StorageLayout, worktree: &WorktreeId) -> PathBuf {
layout.index_cache(worktree)
}
pub fn cache_dir(config: &IndexConfig, canonical: &Path) -> PathBuf {
let hash = Sha256::digest(canonical.to_string_lossy().as_bytes());
let hex = format!("{hash:x}");
let base = config.cache_base.clone().unwrap_or_else(default_cache_base);
base.join("synwire").join("indices").join(hex)
}
pub fn read_meta(cache: &Path) -> Option<IndexMeta> {
let path = cache.join("meta.json");
let data = std::fs::read_to_string(&path).ok()?;
serde_json::from_str(&data).ok()
}
pub fn write_meta(cache: &Path, meta: &IndexMeta) -> std::io::Result<()> {
std::fs::create_dir_all(cache)?;
let json = serde_json::to_string_pretty(meta).map_err(std::io::Error::other)?;
std::fs::write(cache.join("meta.json"), json)
}
fn default_cache_base() -> PathBuf {
directories::BaseDirs::new()
.map_or_else(|| PathBuf::from(".cache"), |d| d.cache_dir().to_path_buf())
}