use std::path::{Path, PathBuf};

use crate::state::PROJECT_STATE_DIR;

/// Walk up from `start` until we find a directory containing `.aimgr/`.
/// Returns None if no such ancestor exists.
pub fn discover_root(start: &Path) -> Option<PathBuf> {
    let mut cur = start;
    loop {
        if cur.join(PROJECT_STATE_DIR).exists() {
            return Some(cur.to_path_buf());
        }
        cur = cur.parent()?;
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::fs;
    use tempfile::tempdir;

    #[test]
    fn discover_finds_nearest_aimgr_ancestor() {
        let tmp = tempdir().unwrap();
        let root = tmp.path();
        fs::create_dir_all(root.join(".aimgr")).unwrap();
        let nested = root.join("a/b/c");
        fs::create_dir_all(&nested).unwrap();
        assert_eq!(discover_root(&nested).unwrap(), root);
    }

    #[test]
    fn discover_returns_none_when_no_ancestor_has_aimgr() {
        let tmp = tempdir().unwrap();
        assert!(discover_root(tmp.path()).is_none());
    }
}
