use std::collections::BTreeMap;
use std::fs;
use std::io;
use std::path::{Path, PathBuf};
use std::time::SystemTime;
use super::files::{Part, entries};
const QUEUES: [&str; 2] = ["pending", "held"];
pub fn trees(home: &Path, tree: &Path) -> Vec<PathBuf> {
let mut trees = vec![home.join("spool"), home.join("profile-spool")];
if !trees.iter().any(|own| own == tree) {
trees.push(tree.to_path_buf());
}
trees
}
pub struct Conversation {
pub tree: PathBuf,
pub id: String,
pub turns: Vec<Closed>,
}
pub struct Closed {
pub directory: PathBuf,
pub n: u64,
pub modified: Option<SystemTime>,
pub reason: bool,
}
pub fn stat(path: &Path) -> io::Result<Option<fs::Metadata>> {
match fs::symlink_metadata(path) {
Ok(metadata) => Ok(Some(metadata)),
Err(error) if error.kind() == io::ErrorKind::NotFound => Ok(None),
Err(error) => Err(error),
}
}
fn listing(directory: &Path) -> io::Result<Vec<fs::DirEntry>> {
match fs::read_dir(directory) {
Ok(listed) => listed.collect(),
Err(error) if error.kind() == io::ErrorKind::NotFound => Ok(Vec::new()),
Err(error) => Err(error),
}
}
pub fn scan(trees: &[PathBuf]) -> io::Result<(u64, Vec<Conversation>)> {
let mut total = 0;
let mut found: BTreeMap<(PathBuf, String), Vec<Closed>> = BTreeMap::new();
for tree in trees {
for entry in listing(tree)? {
if entry.file_name().to_str().is_some_and(|name| {
[".jsonl", ".agy", ".vibe"]
.iter()
.any(|s| name.ends_with(s))
}) {
total += stat(&entry.path())?.map_or(0, |metadata| metadata.len());
}
}
for queue in QUEUES {
for conversation in listing(&tree.join(queue))? {
if !conversation.file_type()?.is_dir() {
continue;
}
let directory = conversation.path();
let id = conversation.file_name().to_string_lossy().into_owned();
for (n, parts) in entries(&directory)? {
let Some((_, file)) = parts.iter().find(|(part, _)| *part == Part::Span) else {
continue;
};
let Some(metadata) = stat(file)? else {
continue;
};
total += metadata.len();
let turns = found.entry((tree.clone(), id.clone())).or_default();
turns.push(Closed {
directory: directory.clone(),
n,
modified: metadata.modified().ok(),
reason: parts.iter().any(|(part, _)| *part == Part::Reason),
});
}
}
}
}
let conversations = found.into_iter().map(|((tree, id), mut turns)| {
turns.sort_by_key(|turn| turn.n);
Conversation { tree, id, turns }
});
Ok((total, conversations.collect()))
}