/// The configured root, if there is one. Split out so `download_dir` and
/// `download_dir_at` cannot drift: on the phone the second is the ONLY way
/// the library is found at all, from a process that has no `AppHandle` to
/// ask.
fn configured_download_dir(cfg: &AppConfig) -> Option<PathBuf> {
    cfg.download_dir
        .as_deref()
        .filter(|d| !d.is_empty())
        .map(PathBuf::from)
}

/// Android's private library root, under the app's own data directory.
///
/// `<dataDir>/Library`, and `dataDir` is what Tauri's `app_data_dir()`
/// resolves to on Android (`PathPlugin.getDataDir` → `activity.dataDir`), so
/// on the phone it is `/data/user/0/com.soulstream.app/Library`. NOT
/// `filesDir`, which is one level deeper — a headless open there finds no
/// database and answers empty with nothing obviously wrong.
#[cfg(target_os = "android")]
fn android_library_root(data_dir: &Path) -> PathBuf {
    data_dir.join("Library")
}

/// `download_dir`, from the app-data directory rather than an `AppHandle` —
/// the headless Android Auto path, which runs in a process with no Tauri in
/// it. `None` means "there is no answer without an app": on the desktop the
/// fallback walks `audio_dir()`/`home_dir()`, which need the handle.
pub fn download_dir_at(data_dir: &Path, cfg: &AppConfig) -> Option<PathBuf> {
    if let Some(d) = configured_download_dir(cfg) {
        return Some(d);
    }
    #[cfg(target_os = "android")]
    let fallback = Some(android_library_root(data_dir));
    #[cfg(not(target_os = "android"))]
    let fallback = {
        let _ = data_dir;
        None
    };
    fallback
}

