/// Parse a config file. One parse, three doors: `load` (an `AppHandle`),
/// `load_at` (a directory) and this. NEVER writes, and never creates
/// anything — `config_path` does a `create_dir_all` and a service-started
/// process reading the config of a library it does not own has no business
/// doing that.
fn load_file(path: &Path) -> AppConfig {
    std::fs::read_to_string(path)
        .ok()
        .and_then(|s| serde_json::from_str(&s).ok())
        .unwrap_or_default()
}

/// The config, from the app-data directory rather than from an `AppHandle`.
///
/// Android Auto starts this process with no Activity, so there IS no
/// `AppHandle` — Kotlin passes `ctx.dataDir` down instead and this is how
/// the headless path reads `download_dir` out of it. Same parse, same
/// silent-default-on-garbage behaviour (a BOM still defeats serde and still
/// yields all-defaults, exactly as it does for `load`).
pub fn load_at(dir: &Path) -> AppConfig {
    load_file(&dir.join("config.json"))
}

pub fn load(app: &tauri::AppHandle) -> AppConfig {
    match config_path(app) {
        Some(path) => load_file(&path),
        None => AppConfig::default(),
    }
}
