//! Prozessabbruch während eines CLI-Exports kontrolliert bis zur Bereinigung führen.
#[cfg(unix)]
pub struct ExportCancel {
    flag: std::sync::Arc<std::sync::atomic::AtomicBool>,
    handlers: Vec<signal_hook::SigId>,
}
#[cfg(unix)]
impl ExportCancel {
    pub fn new() -> std::io::Result<Self> {
        let mut result = Self {
            flag: Default::default(),
            handlers: Vec::new(),
        };
        for signal in [signal_hook::consts::SIGINT, signal_hook::consts::SIGTERM] {
            result
                .handlers
                .push(signal_hook::flag::register(signal, result.flag.clone())?);
        }
        Ok(result)
    }
    pub fn cancelled(&self) -> bool {
        self.flag.load(std::sync::atomic::Ordering::Relaxed)
    }
}
#[cfg(unix)]
impl Drop for ExportCancel {
    fn drop(&mut self) {
        for handler in &self.handlers {
            signal_hook::low_level::unregister(*handler);
        }
    }
}

#[cfg(windows)]
static CANCELLED: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false);
#[cfg(windows)]
unsafe extern "system" fn handle(signal: u32) -> i32 {
    if signal <= 1 {
        CANCELLED.store(true, std::sync::atomic::Ordering::Relaxed);
        1
    } else {
        0
    }
}
#[cfg(windows)]
pub struct ExportCancel;
#[cfg(windows)]
impl ExportCancel {
    pub fn new() -> std::io::Result<Self> {
        CANCELLED.store(false, std::sync::atomic::Ordering::Relaxed);
        // Der CLI-Prozess hat genau einen Export. Win32 ruft den statischen Handler auf.
        if unsafe { windows_sys::Win32::System::Console::SetConsoleCtrlHandler(Some(handle), 1) }
            == 0
        {
            return Err(std::io::Error::last_os_error());
        }
        Ok(Self)
    }
    pub fn cancelled(&self) -> bool {
        CANCELLED.load(std::sync::atomic::Ordering::Relaxed)
    }
}
#[cfg(windows)]
impl Drop for ExportCancel {
    fn drop(&mut self) {
        unsafe {
            windows_sys::Win32::System::Console::SetConsoleCtrlHandler(Some(handle), 0);
        }
    }
}
