use std::path::PathBuf;

/// Resolve the per-user app data directory, following each OS's convention:
///
/// - Windows: `%LOCALAPPDATA%\kon\`           e.g. `C:\Users\Jake\AppData\Local\kon`
/// - macOS:   `~/Library/Application Support/Kon/`
/// - Linux:   `$XDG_DATA_HOME/kon` or `~/.local/share/kon` (XDG Base Directory),
///            with a fallback to the legacy `~/.kon/` if it already exists, so
///            existing installs keep working.
/// - Other Unix: `~/.kon/`
///
/// TODO: Consolidate with `crates/transcription/src/model_manager.rs::dirs_path()`
/// into a shared helper in `crates/core/` to avoid duplicating platform-specific
/// path logic across crates.
pub fn app_data_dir() -> PathBuf {
    #[cfg(target_os = "windows")]
    {
        let local_app_data = std::env::var("LOCALAPPDATA").unwrap_or_else(|_| ".".to_string());
        return PathBuf::from(local_app_data).join("kon");
    }

    #[cfg(target_os = "macos")]
    {
        let home = std::env::var("HOME").unwrap_or_else(|_| "/tmp".to_string());
        return PathBuf::from(home)
            .join("Library")
            .join("Application Support")
            .join("Kon");
    }

    #[cfg(target_os = "linux")]
    {
        let home = std::env::var("HOME").unwrap_or_else(|_| "/tmp".to_string());

        // Honour the legacy ~/.kon/ if it exists on disk so existing
        // installs are not orphaned. New installs follow XDG.
        let legacy = PathBuf::from(&home).join(".kon");
        if legacy.exists() {
            return legacy;
        }

        // XDG Base Directory: $XDG_DATA_HOME/kon or default ~/.local/share/kon
        if let Ok(xdg) = std::env::var("XDG_DATA_HOME") {
            if !xdg.is_empty() {
                return PathBuf::from(xdg).join("kon");
            }
        }
        return PathBuf::from(home).join(".local").join("share").join("kon");
    }

    #[cfg(not(any(target_os = "windows", target_os = "macos", target_os = "linux")))]
    {
        let home = std::env::var("HOME").unwrap_or_else(|_| "/tmp".to_string());
        PathBuf::from(home).join(".kon")
    }
}

/// Path to the SQLite database file.
pub fn database_path() -> PathBuf {
    app_data_dir().join("kon.db")
}

/// Directory for saved audio recordings.
pub fn recordings_dir() -> PathBuf {
    app_data_dir().join("recordings")
}

/// Directory for crash dumps written by the Rust panic hook.
/// Each crash is a single text file: `<unix-ts>-<short-id>.crash`.
/// Used by the diagnostic-report bundler in Settings → About.
pub fn crashes_dir() -> PathBuf {
    app_data_dir().join("crashes")
}

/// Directory for the rolling Rust log file (kon.log + rotated kon.log.1, etc).
/// Subscribers configured in src-tauri/src/lib.rs at startup.
pub fn logs_dir() -> PathBuf {
    app_data_dir().join("logs")
}
