// SPDX-License-Identifier: GPL-3.0-or-later

//! Autostart management — creates/removes .desktop file in ~/.config/autostart/

use anyhow::Result;
use std::fs;
use std::path::PathBuf;

const DESKTOP_ENTRY: &str = "\
[Desktop Entry]
Type=Application
Name=Temperlux
Comment=Brightness controller for displays
Exec=temperlux-gui
Icon=dev.angussoftware.temperlux
Terminal=false
Categories=Settings;HardwareSettings;
X-GNOME-Autostart-enabled=true
Hidden=false
";

/// Get the autostart .desktop file path.
fn autostart_path() -> Result<PathBuf> {
    let config = dirs::config_dir()
        .ok_or_else(|| anyhow::anyhow!("Could not find config directory"))?;
    Ok(config.join("autostart").join("temperlux.desktop"))
}

/// Enable autostart — writes .desktop file to ~/.config/autostart/
pub fn enable() -> Result<()> {
    let path = autostart_path()?;
    if let Some(parent) = path.parent() {
        fs::create_dir_all(parent)?;
    }
    fs::write(&path, DESKTOP_ENTRY)?;
    log::info!("Autostart enabled: {}", path.display());
    Ok(())
}

/// Disable autostart — removes .desktop file from ~/.config/autostart/
pub fn disable() -> Result<()> {
    let path = autostart_path()?;
    if path.exists() {
        fs::remove_file(&path)?;
        log::info!("Autostart disabled: {}", path.display());
    }
    Ok(())
}

/// Check if autostart is currently enabled (file exists).
pub fn is_enabled() -> bool {
    autostart_path().map(|p| p.exists()).unwrap_or(false)
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::fs;

    #[test]
    fn desktop_entry_is_valid() {
        // Ensure our embedded .desktop entry parses as valid INI-ish
        assert!(DESKTOP_ENTRY.contains("Type=Application"));
        assert!(DESKTOP_ENTRY.contains("Exec=temperlux-gui"));
        assert!(DESKTOP_ENTRY.contains("Name=Temperlux"));
    }

    #[test]
    fn enable_disable_roundtrip() {
        let tmp = tempfile::tempdir().unwrap();
        let path = tmp.path().join("autostart").join("temperlux.desktop");

        // Write
        fs::create_dir_all(path.parent().unwrap()).unwrap();
        fs::write(&path, DESKTOP_ENTRY).unwrap();
        assert!(path.exists());

        // Remove
        fs::remove_file(&path).unwrap();
        assert!(!path.exists());
    }
}
