use super::CrateFetcher;
use crate::models::ScanCrateError;
use crate::utils::find_crate_src_path;
use async_trait::async_trait;
use std::path::PathBuf;

#[derive(Debug, Clone, Default)]
pub struct WorkspaceFetcher;

impl WorkspaceFetcher {
    #[must_use]
    pub fn new() -> Self {
        Self
    }
}

#[async_trait]
impl CrateFetcher for WorkspaceFetcher {
    async fn fetch_crate_src(
        &self,
        name: &str,
        version_req: Option<&str>,
    ) -> Result<PathBuf, ScanCrateError> {
        log::info!(
            "Attempting to find '{}' in workspace dependencies (version: {:?})",
            name,
            version_req
        );
        
        // Use the existing find_crate_src_path function which uses cargo metadata
        match find_crate_src_path(name, version_req) {
            Ok(path) => {
                log::info!("Found '{name}' in workspace at: {path:?}");
                Ok(path)
            }
            Err(e) => {
                log::debug!("Failed to find '{name}' in workspace: {e}");
                Err(ScanCrateError::CrateSourceNotFound {
                    name: name.to_string(),
                    version_spec: version_req.unwrap_or("any").to_string(),
                    source: anyhow::anyhow!("Not found in workspace dependencies: {}", e),
                })
            }
        }
    }
}