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

/// Strong markers that definitively identify a project root.
const STRONG_MARKERS: &[&str] = &["botignore.toml", ".botignore.toml", ".git"];

/// Walk upward from `target` (or its parent if `target` is a file) looking
/// for the nearest project root. Strong markers (`botignore.toml`,
/// `.botignore.toml`, `.git`) stop the walk immediately. A `.botignore`
/// file is remembered as a fallback but does not stop the walk — the search
/// continues upward for a stronger boundary. If none is found, the
/// `.botignore` location is used.
pub fn find_project_root(target: &Path) -> Option<PathBuf> {
    let start = if target.is_file() {
        target.parent()?
    } else {
        target
    };

    let mut fallback: Option<PathBuf> = None;
    let mut current = Some(start);
    while let Some(dir) = current {
        for marker in STRONG_MARKERS {
            if dir.join(marker).exists() {
                return Some(dir.to_path_buf());
            }
        }
        if fallback.is_none() && dir.join(".botignore").exists() {
            fallback = Some(dir.to_path_buf());
        }
        current = dir.parent();
    }
    fallback
}
