use std::path::PathBuf;
use tokio::process::Command;

pub async fn change_to_workspace_dir() -> Result<(), Box<dyn std::error::Error>> {
    // Use cargo to find the workspace root
    let output = Command::new("cargo")
        .args(["locate-project", "--workspace", "--message-format=plain"])
        .output()
        .await?;

    if !output.status.success() {
        return Err(format!(
            "Failed to locate workspace: {}",
            String::from_utf8_lossy(&output.stderr)
        )
        .into());
    }

    let workspace_cargo_toml = String::from_utf8(output.stdout)?;
    let workspace_cargo_toml = workspace_cargo_toml.trim();

    // Get the directory containing Cargo.toml
    let workspace_dir = PathBuf::from(workspace_cargo_toml)
        .parent()
        .ok_or("Failed to get workspace directory")?
        .to_path_buf();

    println!(
        "Changing to workspace directory: {}",
        workspace_dir.display()
    );
    std::env::set_current_dir(&workspace_dir)?;

    Ok(())
}
