// Copyright (C) 2025 Christian Mauduit <ufoot@ufoot.org>

//! Test utilities for finding test data files.

#[cfg(all(test, feature = "image"))]
use std::path::{Path, PathBuf};

/// Finds the testdata directory relative to the project root.
///
/// This function searches upward from the current directory until it finds
/// a directory containing both Cargo.toml and testdata/, ensuring tests
/// work regardless of where they're run from.
#[cfg(all(test, feature = "image"))]
pub fn find_testdata_dir() -> PathBuf {
    let mut current = std::env::current_dir().expect("Failed to get current directory");

    loop {
        let testdata = current.join("testdata");
        let cargo_toml = current.join("Cargo.toml");

        if testdata.exists() && cargo_toml.exists() {
            return testdata;
        }

        if !current.pop() {
            panic!("Could not find testdata directory. Make sure tests are run from the project root.");
        }
    }
}

/// Gets the path to a test file within testdata.
///
/// # Example
///
/// ```ignore
/// let path = testdata_path("2d/a-32x24.jpg");
/// ```
#[cfg(all(test, feature = "image"))]
pub fn testdata_path<P: AsRef<Path>>(relative_path: P) -> PathBuf {
    find_testdata_dir().join(relative_path)
}
