use std::process::Command;
use tauri::command;

#[command]
pub async fn send_notify_send(title: String, body: String) -> Result<(), String> {
    // Use notify-send for Linux/WSL
    let output = Command::new("notify-send")
        .arg(&title)
        .arg(&body)
        .arg("--urgency=normal")
        .arg("--app-name=Hikari Desktop")
        .output()
        .map_err(|e| {
            format!(
                "Failed to execute notify-send: {}. Make sure libnotify-bin is installed.",
                e
            )
        })?;

    if !output.status.success() {
        let error = String::from_utf8_lossy(&output.stderr);
        return Err(format!("notify-send failed: {}", error));
    }

    Ok(())
}

#[command]
pub async fn send_windows_notification(title: String, body: String) -> Result<(), String> {
    // Create PowerShell script for Windows Toast Notification
    let ps_script = format!(
        r#"
[Windows.UI.Notifications.ToastNotificationManager, Windows.UI.Notifications, ContentType = WindowsRuntime] > $null
[Windows.Data.Xml.Dom.XmlDocument, Windows.Data.Xml.Dom.XmlDocument, ContentType = WindowsRuntime] > $null

$APP_ID = 'Hikari Desktop'

$template = @"
<toast>
    <visual>
        <binding template="ToastText02">
            <text id="1">{}</text>
            <text id="2">{}</text>
        </binding>
    </visual>
    <audio src="ms-winsoundevent:Notification.Default" />
</toast>
"@

$xml = New-Object Windows.Data.Xml.Dom.XmlDocument
$xml.LoadXml($template)

$toast = New-Object Windows.UI.Notifications.ToastNotification $xml
[Windows.UI.Notifications.ToastNotificationManager]::CreateToastNotifier($APP_ID).Show($toast)
"#,
        title.replace("\"", "`\""),
        body.replace("\"", "`\"")
    );

    // Try PowerShell Core first (pwsh), then fall back to Windows PowerShell
    let output = Command::new("pwsh.exe")
        .arg("-NoProfile")
        .arg("-WindowStyle")
        .arg("Hidden")
        .arg("-Command")
        .arg(&ps_script)
        .output()
        .or_else(|_| {
            Command::new("powershell.exe")
                .arg("-NoProfile")
                .arg("-WindowStyle")
                .arg("Hidden")
                .arg("-Command")
                .arg(&ps_script)
                .output()
        })
        .map_err(|e| format!("Failed to execute PowerShell: {}", e))?;

    if !output.status.success() {
        let error = String::from_utf8_lossy(&output.stderr);
        return Err(format!("PowerShell script failed: {}", error));
    }

    Ok(())
}

// Alternative: Use Windows built-in MSG command for simple notifications
#[command]
pub async fn send_simple_notification(title: String, body: String) -> Result<(), String> {
    let message = format!("{}\n\n{}", title, body);

    Command::new("cmd.exe")
        .arg("/c")
        .arg("msg")
        .arg("*")
        .arg(&message)
        .output()
        .map_err(|e| format!("Failed to send message: {}", e))?;

    Ok(())
}
