use std::collections::HashMap;
use std::path::{Path, PathBuf};
use chrono::{DateTime, Utc};
use serde::{Deserialize, Serialize};
use serde_json::Value;
#[derive(Debug, Clone, Serialize, Deserialize)]
pub(crate) struct AssistantRecord {
pub assistant_id: String,
pub name: String,
pub graph: String,
#[serde(default)]
pub config: Value,
#[serde(default)]
pub metadata: Value,
pub created_at: DateTime<Utc>,
}
pub(crate) fn dir(store_root: &Path) -> PathBuf {
store_root.join("assistants")
}
pub(crate) fn load(store_root: &Path) -> HashMap<String, AssistantRecord> {
let mut out = HashMap::new();
let mut files = Vec::new();
collect_json_files(&dir(store_root), &mut files);
for path in files {
let parsed = std::fs::read_to_string(&path)
.ok()
.and_then(|raw| serde_json::from_str::<AssistantRecord>(&raw).ok());
match parsed {
Some(record) => {
out.insert(record.assistant_id.clone(), record);
}
None => {
tracing::warn!(path = %path.display(), "skipping unreadable assistant file")
}
}
}
out
}
fn collect_json_files(root: &Path, out: &mut Vec<PathBuf>) {
let Ok(entries) = std::fs::read_dir(root) else {
return;
};
for entry in entries.flatten() {
let path = entry.path();
if path.is_dir() {
collect_json_files(&path, out);
} else if path.extension().and_then(|e| e.to_str()) == Some("json") {
out.push(path);
}
}
}
pub(crate) async fn persist(store_root: &Path, record: &AssistantRecord) -> std::io::Result<()> {
let path = dir(store_root).join(format!("{}.json", record.assistant_id));
if let Some(parent) = path.parent() {
tokio::fs::create_dir_all(parent).await?;
}
let raw = serde_json::to_vec_pretty(record).expect("assistant serialization is infallible");
tokio::fs::write(path, raw).await
}