use std::path::PathBuf;

/// Resolve the directory the running EXE lives in. Falls back to the
/// process working directory if for some reason we can't read
/// `current_exe()` (sandboxed environments, etc.).
fn exe_dir() -> PathBuf {
    std::env::current_exe()
        .ok()
        .and_then(|p| p.parent().map(|p| p.to_path_buf()))
        .unwrap_or_else(|| std::env::current_dir().unwrap_or_default())
}

/// Configure all the env vars Tauri + WebView2 + the OS read when
/// resolving "where do I put my data" so EVERYTHING lands in a single
/// `./data/` folder next to the EXE - no AppData, no registry, no
/// hidden state. Has to run BEFORE the Tauri builder constructs the
/// webview, since WebView2 reads `WEBVIEW2_USER_DATA_FOLDER` only at
/// startup.
fn redirect_data_to_portable_folder() {
    let root = exe_dir().join("data");
    let _ = std::fs::create_dir_all(&root);

    let appdata = root.join("appdata");
    let local_appdata = root.join("localappdata");
    let webview2 = root.join("webview2");
    let cache = root.join("cache");
    let temp = root.join("temp");

    for d in [&appdata, &local_appdata, &webview2, &cache, &temp] {
        let _ = std::fs::create_dir_all(d);
    }

    // Tauri's path resolver uses the `dirs` crate under the hood, which
    // reads APPDATA / LOCALAPPDATA on Windows. Redirecting these
    // catches every plugin that calls `app.path().app_config_dir()`,
    // `app_data_dir()`, `app_local_data_dir()`, etc. - including
    // tauri-plugin-store and tauri-plugin-window-state.
    std::env::set_var("APPDATA", &appdata);
    std::env::set_var("LOCALAPPDATA", &local_appdata);

    // WebView2's own user data folder. This is where localStorage,
    // IndexedDB, cookies, the HTTP cache, and the GPU shader cache go.
    // Almost all our persisted state (zustand-persist stores) lives
    // here, so this is the most important one to redirect.
    std::env::set_var("WEBVIEW2_USER_DATA_FOLDER", &webview2);

    // TEMP / TMP redirection so any temporary files (rare, but Tauri's
    // file dialog plugin uses these) don't leak to %TEMP%.
    std::env::set_var("TEMP", &temp);
    std::env::set_var("TMP", &temp);

    // XDG variants for Linux portability if we ever ship there.
    std::env::set_var("XDG_DATA_HOME", &local_appdata);
    std::env::set_var("XDG_CONFIG_HOME", &appdata);
    std::env::set_var("XDG_CACHE_HOME", &cache);
}

#[cfg_attr(mobile, tauri::mobile_entry_point)]
pub fn run() {
    redirect_data_to_portable_folder();

    tauri::Builder::default()
        .plugin(tauri_plugin_store::Builder::default().build())
        .plugin(tauri_plugin_window_state::Builder::default().build())
        .run(tauri::generate_context!())
        .expect("error while running tauri application");
}
