use crate::config::AppConfig;
use crate::domain::MatchedProject;
use std::path::Path;

pub fn match_project(config: &AppConfig, cwd: &Path) -> Option<MatchedProject> {
    let normalized_cwd = cwd.canonicalize().unwrap_or_else(|_| cwd.to_path_buf());
    let mut best_match: Option<(&crate::config::ProjectConfig, &std::path::PathBuf)> = None;

    for project in &config.projects {
        for repo_path in &project.repo_paths {
            if normalized_cwd.starts_with(repo_path) {
                match best_match {
                    Some((_, current_repo_path))
                        if current_repo_path.as_os_str().len() >= repo_path.as_os_str().len() => {}
                    _ => best_match = Some((project, repo_path)),
                }
            }
        }
    }

    best_match.map(|(project, repo_path)| MatchedProject {
        id: project.id.clone(),
        name: project.name.clone(),
        reason: format!("cwd matched repo_path {}", repo_path.display()),
    })
}
