use crate::util::{playwright, webdriver};
use std::time::Duration;
use tokio::sync::mpsc;

const DEFAULT_TIMEOUT: Duration = Duration::from_secs(30);

/// Races chromiumoxide (webdriver) and Playwright against each other.
/// Navigates to `url` and returns the `src` attribute of the first element
/// matched by `xpath` — whichever backend resolves it first wins.
pub async fn wait_for_src(url: &str, xpath: &str) -> Option<String> {
    wait_for_attribute(url, xpath, "src", DEFAULT_TIMEOUT).await
}

/// Like [`wait_for_src`] but lets the caller choose the attribute name and timeout.
pub async fn wait_for_attribute(
    url: &str,
    xpath: &str,
    attribute: &str,
    wait_timeout: Duration,
) -> Option<String> {
    // Buffer of 1: the first send wins; the losing task's send is silently
    // dropped when the receiver is gone.
    let (tx, mut rx) = mpsc::channel::<String>(1);

    let (u, x, a) = (url.to_string(), xpath.to_string(), attribute.to_string());
    let tx1 = tx.clone();
    tokio::spawn(async move {
        if let Some(src) = webdriver::wait_for_attribute(&u, &x, &a, wait_timeout).await {
            let _ = tx1.send(src).await;
        }
    });

    let (u, x, a) = (url.to_string(), xpath.to_string(), attribute.to_string());
    tokio::spawn(async move {
        if let Some(src) = playwright::wait_for_attribute(&u, &x, &a, wait_timeout).await {
            let _ = tx.send(src).await;
        }
    });

    rx.recv().await
}
