impl InputAggregator {
    pub fn new(
        dev_mode: bool,
        kbd_tx: Sender<KeyboardReport>,
        mou_tx: Sender<MouseReport>,
        paste_tx: Option<UnboundedSender<String>>,
    ) -> Self {
        Self::new_with_capture_mode(dev_mode, kbd_tx, mou_tx, paste_tx, true)
    }

    pub fn new_with_capture_mode(
        dev_mode: bool,
        kbd_tx: Sender<KeyboardReport>,
        mou_tx: Sender<MouseReport>,
        paste_tx: Option<UnboundedSender<String>>,
        capture_remote_boot: bool,
    ) -> Self {
        let quick_toggle_key = quick_toggle_key_from_env();
        #[cfg(not(coverage))]
        let routing_control_path = launcher_routing_path_from_env("LESAVKA_LAUNCHER_INPUT_CONTROL");
        #[cfg(not(coverage))]
        let routing_state_path = launcher_routing_path_from_env("LESAVKA_LAUNCHER_INPUT_STATE");
        #[cfg(not(coverage))]
        let quick_toggle_control_path =
            launcher_routing_path_from_env("LESAVKA_LAUNCHER_TOGGLE_KEY_CONTROL");
        #[cfg(not(coverage))]
        let clipboard_control_path =
            launcher_routing_path_from_env("LESAVKA_LAUNCHER_CLIPBOARD_CONTROL");
        #[cfg(not(coverage))]
        let wake_control_path = launcher_routing_path_from_env("LESAVKA_LAUNCHER_WAKE_CONTROL");
        #[cfg(not(coverage))]
        let last_wake_request_raw = wake_control_path
            .as_deref()
            .and_then(read_launcher_control_snapshot);
        #[cfg(not(coverage))]
        let wake_interval = last_wake_request_raw.as_deref().and_then(parse_wake_interval);
        #[cfg(coverage)]
        let wake_interval = None;
        let remote_failsafe_timeout = remote_failsafe_timeout_from_env();
        Self {
            kbd_tx,
            mou_tx,
            dev_mode,
            released: !capture_remote_boot,
            magic_active: false,
            pending_release: false,
            pending_kill: false,
            pending_keys: HashSet::new(),
            last_keyboard_report: [0; 8],
            paste_tx,
            keyboards: Vec::new(),
            mice: Vec::new(),
            selected_keyboard_path: input_device_override_from_env("LESAVKA_KEYBOARD_DEVICE"),
            selected_mouse_path: input_device_override_from_env("LESAVKA_MOUSE_DEVICE"),
            #[cfg(not(coverage))]
            known_input_paths: HashMap::new(),
            capture_remote_boot,
            quick_toggle_key,
            quick_toggle_down: false,
            quick_toggle_debounce: quick_toggle_debounce_from_env(),
            last_quick_toggle_at: None,
            pending_release_started_at: None,
            pending_release_timeout: pending_release_timeout_from_env(),
            remote_failsafe_started_at: (capture_remote_boot && !remote_failsafe_timeout.is_zero())
                .then(Instant::now),
            remote_failsafe_timeout,
            #[cfg(not(coverage))]
            last_routing_request_raw: routing_control_path
                .as_deref()
                .and_then(read_launcher_control_snapshot),
            #[cfg(not(coverage))]
            routing_control_path,
            #[cfg(not(coverage))]
            last_quick_toggle_request_raw: quick_toggle_control_path
                .as_deref()
                .and_then(read_launcher_control_snapshot),
            #[cfg(not(coverage))]
            quick_toggle_control_path,
            #[cfg(not(coverage))]
            clipboard_control_marker: clipboard_control_path
                .as_deref()
                .map(path_marker)
                .unwrap_or_default(),
            #[cfg(not(coverage))]
            clipboard_control_path,
            #[cfg(not(coverage))]
            wake_control_path,
            #[cfg(not(coverage))]
            last_wake_request_raw,
            wake_interval,
            last_hid_relayed_at: Instant::now(),
            wake_nonce: 0,
            #[cfg(not(coverage))]
            routing_state_path,
            #[cfg(not(coverage))]
            published_remote_capture: None,
            remote_capture_enabled: Arc::new(AtomicBool::new(capture_remote_boot)),
        }
    }

    pub fn remote_capture_enabled_handle(&self) -> Arc<AtomicBool> {
        Arc::clone(&self.remote_capture_enabled)
    }

    #[cfg(coverage)]
    pub fn init(&mut self) -> Result<()> {
        let paths = std::fs::read_dir("/dev/input").context("Failed to read /dev/input")?;
        for path in paths.flatten().map(|entry| entry.path()) {
            if !path
                .file_name()
                .map(|f| f.to_string_lossy().starts_with("event"))
                .unwrap_or(false)
            {
                continue;
            }
            if let Ok(dev) = Device::open(&path) {
                let _ = dev.set_nonblocking(true);
                match classify_device(&dev) {
                    DeviceKind::Keyboard => {
                        if !matches_selected_input_device(
                            &path,
                            self.selected_keyboard_path.as_deref(),
                        ) {
                            continue;
                        }
                        let mut aggregator = KeyboardAggregator::new(
                            dev,
                            self.dev_mode,
                            self.kbd_tx.clone(),
                            self.paste_tx.clone(),
                        );
                        aggregator.set_send(self.capture_remote_boot);
                        if !self.capture_remote_boot {
                            aggregator.set_grab(false);
                        }
                        self.keyboards.push(aggregator);
                    }
                    DeviceKind::Mouse => {
                        if !matches_selected_input_device(
                            &path,
                            self.selected_mouse_path.as_deref(),
                        ) {
                            continue;
                        }
                        let mut aggregator =
                            MouseAggregator::new(dev, self.dev_mode, self.mou_tx.clone());
                        aggregator.set_send(self.capture_remote_boot);
                        if !self.capture_remote_boot {
                            aggregator.set_grab(false);
                        }
                        self.mice.push(aggregator);
                    }
                    DeviceKind::Other => {}
                }
            }
        }
        Ok(())
    }

    #[cfg(not(coverage))]
    pub fn init(&mut self) -> Result<()> {
        let found_any = self.scan_input_devices(self.capture_remote_boot, true)?;

        if !found_any {
            bail!("No suitable keyboard/mouse devices found or none grabbed.");
        }

        Ok(())
    }

    #[cfg(not(coverage))]
    fn scan_input_devices(&mut self, remote_active: bool, fail_grab: bool) -> Result<bool> {
        let paths = std::fs::read_dir("/dev/input").context("Failed to read /dev/input")?;
        let mut found_any = false;

        for entry in paths {
            let entry = entry?;
            let path = entry.path();

            if !path
                .file_name()
                .is_some_and(|f| f.to_string_lossy().starts_with("event"))
            {
                continue;
            }
            let identity = input_device_identity(&path).unwrap_or_default();
            if self
                .known_input_paths
                .get(&path)
                .is_some_and(|known| *known == identity)
            {
                continue;
            }

            let mut dev = match Device::open(&path) {
                Ok(d) => d,
                Err(e) => {
                    warn!("❌ open {}: {e}", path.display());
                    continue;
                }
            };

            dev.set_nonblocking(true)
                .with_context(|| format!("set_non_blocking {:?}", path))?;

            match classify_device(&dev) {
                DeviceKind::Keyboard => {
                    if !matches_selected_input_device(&path, self.selected_keyboard_path.as_deref())
                    {
                        self.known_input_paths.insert(path, identity);
                        continue;
                    }
                    if remote_active {
                        if let Err(err) = dev.grab() {
                            if fail_grab {
                                return Err(err)
                                    .with_context(|| format!("grabbing keyboard {path:?}"));
                            }
                            warn!("❌ grab keyboard {}: {err}", path.display());
                            continue;
                        }
                        info!(
                            "🤏🖱️ Grabbed keyboard {:?}",
                            dev.name().unwrap_or("UNKNOWN")
                        );
                    } else {
                        info!(
                            "⌨️ local-input mode; keyboard staged ungrabbed {:?}",
                            dev.name().unwrap_or("UNKNOWN")
                        );
                    }

                    let mut kbd_agg = KeyboardAggregator::new(
                        dev,
                        self.dev_mode,
                        self.kbd_tx.clone(),
                        self.paste_tx.clone(),
                    );
                    kbd_agg.set_send(remote_active);
                    if !remote_active {
                        kbd_agg.set_grab(false);
                    }
                    self.known_input_paths.insert(path, identity);
                    self.keyboards.push(kbd_agg);
                    found_any = true;
                }
                DeviceKind::Mouse => {
                    if !matches_selected_input_device(&path, self.selected_mouse_path.as_deref()) {
                        self.known_input_paths.insert(path, identity);
                        continue;
                    }
                    if remote_active {
                        if let Err(err) = dev.grab() {
                            if fail_grab {
                                return Err(err)
                                    .with_context(|| format!("grabbing mouse {path:?}"));
                            }
                            warn!("❌ grab mouse {}: {err}", path.display());
                            continue;
                        }
                        info!("🤏⌨️ Grabbed mouse {:?}", dev.name().unwrap_or("UNKNOWN"));
                    } else {
                        info!(
                            "🖱️ local-input mode; mouse staged ungrabbed {:?}",
                            dev.name().unwrap_or("UNKNOWN")
                        );
                    }

                    let mut mouse_agg =
                        MouseAggregator::new(dev, self.dev_mode, self.mou_tx.clone());
                    mouse_agg.set_send(remote_active);
                    if !remote_active {
                        mouse_agg.set_grab(false);
                    }
                    self.known_input_paths.insert(path, identity);
                    self.mice.push(mouse_agg);
                    found_any = true;
                }
                DeviceKind::Other => {
                    debug!(
                        "Skipping non-kbd/mouse device: {:?}",
                        dev.name().unwrap_or("UNKNOWN")
                    );
                    self.known_input_paths.insert(path, identity);
                }
            }
        }

        Ok(found_any)
    }

}
