use crate::fact::MemoFact;
use anyhow::Result;
use std::path::{Path, PathBuf};

pub struct ProjectStore {
    path: PathBuf,
}

impl ProjectStore {
    pub fn new(root: &Path, project_hash: &str) -> Self {
        let path = dirs_base(root).join(project_hash);
        Self { path }
    }

    pub fn save_crystallized(&self, facts: &[MemoFact]) -> Result<()> {
        std::fs::create_dir_all(&self.path)?;
        let json = serde_json::to_string_pretty(facts)?;
        std::fs::write(self.path.join("crystallized.json"), json)?;
        Ok(())
    }

    pub fn load_crystallized(&self) -> Result<Vec<MemoFact>> {
        let p = self.path.join("crystallized.json");
        if !p.exists() {
            return Ok(Vec::new());
        }
        let json = std::fs::read_to_string(p)?;
        Ok(serde_json::from_str(&json)?)
    }
}

fn dirs_base(root: &Path) -> PathBuf {
    root.join(".bctx").join("vault")
}
