use std::io::Write;
use std::process::Command;
use tauri::command;
use tempfile::NamedTempFile;

#[command]
pub async fn send_vbs_notification(title: String, body: String) -> Result<(), String> {
    // Create a VBScript that shows a Windows notification
    let vbs_content = format!(
        r#"
Set objShell = CreateObject("WScript.Shell")
objShell.Popup "{}" & vbCrLf & vbCrLf & "{}", 5, "{}", 64
"#,
        body.replace("\"", "\"\"").replace("\n", "\" & vbCrLf & \""),
        title.replace("\"", "\"\""),
        title.replace("\"", "\"\"")
    );

    // Create a temporary VBS file
    let mut temp_file =
        NamedTempFile::new().map_err(|e| format!("Failed to create temp file: {}", e))?;

    temp_file
        .write_all(vbs_content.as_bytes())
        .map_err(|e| format!("Failed to write VBS content: {}", e))?;

    let temp_path = temp_file.path().to_string_lossy().to_string();

    // Convert WSL path to Windows path
    let windows_path = if temp_path.starts_with("/mnt/") {
        // Convert /mnt/c/... to C:\...
        let path_parts: Vec<&str> = temp_path.split('/').collect();
        if path_parts.len() > 2 {
            let drive_letter = path_parts[2].to_uppercase();
            let rest_of_path = path_parts[3..].join("\\");
            format!("{}:\\{}", drive_letter, rest_of_path)
        } else {
            temp_path.clone()
        }
    } else if temp_path.starts_with("/tmp/") {
        // WSL temp files might be in a different location
        // Try to use wslpath to convert
        let output = Command::new("wslpath").arg("-w").arg(&temp_path).output();

        if let Ok(result) = output {
            if result.status.success() {
                String::from_utf8_lossy(&result.stdout).trim().to_string()
            } else {
                temp_path.clone()
            }
        } else {
            temp_path.clone()
        }
    } else {
        temp_path.clone()
    };

    // Execute the VBScript using wscript.exe
    let output = Command::new("/mnt/c/Windows/System32/wscript.exe")
        .arg("//NoLogo")
        .arg(&windows_path)
        .output()
        .map_err(|e| format!("Failed to execute VBScript: {}", e))?;

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

    Ok(())
}
