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

#[command]
pub async fn send_wsl_notification(title: String, body: String) -> Result<(), String> {
    // Method 1: Try Windows 10/11 toast notification using PowerShell
    let toast_command = format!(
        r#"
Add-Type -AssemblyName System.Runtime.WindowsRuntime
$null = [Windows.UI.Notifications.ToastNotificationManager, Windows.UI.Notifications, ContentType = WindowsRuntime]
$null = [Windows.Data.Xml.Dom.XmlDocument, Windows.Data.Xml.Dom.XmlDocument, ContentType = WindowsRuntime]

$APP_ID = 'Hikari Desktop'

$template = @"
<toast>
    <visual>
        <binding template="ToastGeneric">
            <text>{0}</text>
            <text>{1}</text>
        </binding>
    </visual>
</toast>
"@

$xml = New-Object Windows.Data.Xml.Dom.XmlDocument
$xml.LoadXml($template -f ('{0}' -replace "'", "''"), ('{1}' -replace "'", "''"))

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

    // Try PowerShell.exe through WSL
    let output = Command::new("/mnt/c/Windows/System32/WindowsPowerShell/v1.0/powershell.exe")
        .arg("-NoProfile")
        .arg("-ExecutionPolicy")
        .arg("Bypass")
        .arg("-WindowStyle")
        .arg("Hidden")
        .arg("-Command")
        .arg(&toast_command)
        .output();

    match output {
        Ok(result) => {
            if result.status.success() {
                println!("WSL notification sent successfully");
                return Ok(());
            } else {
                let stderr = String::from_utf8_lossy(&result.stderr);
                println!("PowerShell toast failed: {}", stderr);
            }
        }
        Err(e) => {
            println!("Failed to run PowerShell: {}", e);
        }
    }

    // Skip msg.exe as it creates alert boxes
    // Method 2 removed

    // Method 3: Try wsl-notify-send if available
    let notify_result = Command::new("wsl-notify-send")
        .arg("--appId")
        .arg("HikariDesktop")
        .arg("--category")
        .arg(&title)
        .arg(&body)
        .output();

    if let Ok(result) = notify_result {
        if result.status.success() {
            println!("Notification sent via wsl-notify-send");
            return Ok(());
        }
    }

    // If all methods fail, return an error
    Err("All WSL notification methods failed".to_string())
}
