//! IPC communication with ostp-daemon via Named Pipe

use anyhow::{Context, Result};
use std::io::{Read, Write};

const PIPE_NAME: &str = r"\\.\pipe\ostp-daemon";

pub async fn send_command(command: &str) -> Result<String> {
    #[cfg(windows)]
    {
        use std::fs::OpenOptions;
        use std::os::windows::fs::OpenOptionsExt;
        use winapi::um::winbase::FILE_FLAG_OVERLAPPED;

        // Connect to Named Pipe
        let mut pipe = OpenOptions::new()
            .read(true)
            .write(true)
            .custom_flags(FILE_FLAG_OVERLAPPED)
            .open(PIPE_NAME)
            .context("Failed to connect to ostp-daemon. Is the service running?")?;

        // Send command
        pipe.write_all(command.as_bytes())?;
        pipe.write_all(b"\n")?;
        pipe.flush()?;

        // Read response
        let mut response = String::new();
        pipe.read_to_string(&mut response)?;

        Ok(response.trim().to_string())
    }

    #[cfg(not(windows))]
    {
        anyhow::bail!("Named pipes are only supported on Windows");
    }
}
