impl InputAggregator {
    fn toggle_grab(&mut self) {
        if self.pending_release || self.pending_kill {
            return;
        }
        if self.released {
            tracing::info!("🧙  magic chord - restricting devices 🪄 IMPERIUS!!! 🎮🔒");
        } else {
            tracing::info!("🧙  magic chord - freeing devices 🪄 EXPELLIARMUS!!! 🔓🕊️");
        }
        if self.released {
            self.enable_remote_capture();
            #[cfg(not(coverage))]
            self.publish_routing_state_if_changed();
        } else {
            self.begin_local_release();
        }
    }

    fn enable_remote_capture(&mut self) {
        self.remote_capture_enabled.store(true, Ordering::Relaxed);
        for k in &mut self.keyboards {
            k.reset_state();
            k.set_send(true);
            k.set_grab(true);
        }
        for m in &mut self.mice {
            m.reset_state();
            m.set_send(true);
            m.set_grab(true);
        }
        self.released = false;
        self.pending_release = false;
        self.pending_release_started_at = None;
        self.pending_keys.clear();
        self.remote_failsafe_started_at =
            (!self.remote_failsafe_timeout.is_zero()).then(Instant::now);
        if !self.remote_failsafe_timeout.is_zero() {
            info!(
                "🛟 remote input failsafe armed for {} ms while the swap key path is being re-validated",
                self.remote_failsafe_timeout.as_millis()
            );
        }
        self.last_keyboard_report = [0; 8];
    }

    fn begin_local_release(&mut self) {
        if self.released && !self.pending_release {
            #[cfg(not(coverage))]
            self.publish_routing_state_if_changed();
            return;
        }
        self.remote_failsafe_started_at = None;
        self.remote_capture_enabled.store(false, Ordering::Relaxed);
        for k in &mut self.keyboards {
            k.send_empty_report();
            k.set_send(false);
        }
        for m in &mut self.mice {
            m.reset_state();
            m.set_send(false);
        }
        self.pending_release = true;
        self.pending_release_started_at = Some(Instant::now());
        self.last_keyboard_report = [0; 8];
        self.capture_pending_keys();
        #[cfg(not(coverage))]
        self.publish_routing_state_if_changed();
    }

    fn finish_local_release(&mut self, focus_launcher: bool) {
        for k in &mut self.keyboards {
            k.set_grab(false);
            k.reset_state();
        }
        for m in &mut self.mice {
            m.set_grab(false);
            m.reset_state();
        }
        self.released = true;
        self.pending_release = false;
        self.pending_release_started_at = None;
        self.pending_keys.clear();
        self.remote_failsafe_started_at = None;
        if focus_launcher {
            #[cfg(not(coverage))]
            focus_launcher_on_local_if_enabled();
        }
        #[cfg(not(coverage))]
        self.publish_routing_state_if_changed();
    }

    fn pending_release_timed_out(&self) -> bool {
        (self.pending_release || self.pending_kill)
            && self
                .pending_release_started_at
                .is_some_and(|started_at| started_at.elapsed() >= self.pending_release_timeout)
    }

    fn remote_failsafe_expired(&self) -> bool {
        !self.released
            && !self.pending_release
            && !self.pending_kill
            && !self.remote_failsafe_timeout.is_zero()
            && self
                .remote_failsafe_started_at
                .is_some_and(|started_at| started_at.elapsed() >= self.remote_failsafe_timeout)
    }

    fn remote_capture_active(&self) -> bool {
        !self.released
            && !self.pending_release
            && !self.pending_kill
            && self.remote_capture_enabled.load(Ordering::Relaxed)
    }

    fn capture_pending_keys(&mut self) {
        self.pending_keys.clear();
        for k in &self.keyboards {
            for key in k.pressed_keys_snapshot() {
                self.pending_keys.insert(key);
            }
        }
    }

    fn process_keyboard_updates(&mut self) {
        for index in 0..self.keyboards.len() {
            let mut keyboard_shadow: HashSet<KeyCode> = self.keyboards[index]
                .pressed_keys_snapshot()
                .into_iter()
                .collect();
            let other_pressed: HashSet<KeyCode> = self
                .keyboards
                .iter()
                .enumerate()
                .filter(|(other_index, _)| *other_index != index)
                .flat_map(|(_, keyboard)| keyboard.pressed_keys_snapshot())
                .collect();
            let updates = {
                let keyboard = &mut self.keyboards[index];
                keyboard.drain_key_updates()
            };
            for update in updates {
                update_shadow_pressed_keys(&mut keyboard_shadow, update.code, update.value);
                if update.swallowed || !self.keyboard_capture_enabled() {
                    continue;
                }
                let report = build_keyboard_report(
                    other_pressed
                        .iter()
                        .copied()
                        .chain(keyboard_shadow.iter().copied()),
                );
                if report == self.last_keyboard_report {
                    continue;
                }
                emit_live_keyboard_report(&self.kbd_tx, update.code, update.value, report);
                self.last_keyboard_report = report;
                self.record_hid_relayed();
            }
        }
    }

    fn keyboard_capture_enabled(&self) -> bool {
        self.keyboards
            .iter()
            .any(KeyboardAggregator::sending_enabled)
    }

    fn quick_toggle_active(&mut self) -> bool {
        self.quick_toggle_key.is_some_and(|key| {
            self.keyboards
                .iter_mut()
                .any(|kbd| kbd.take_key_activation(key))
        })
    }

    fn observe_quick_toggle(&mut self, quick_toggle_now: bool) {
        if quick_toggle_now && !self.quick_toggle_down {
            let now = Instant::now();
            let debounced = self
                .last_quick_toggle_at
                .is_none_or(|last| now.duration_since(last) >= self.quick_toggle_debounce);
            if debounced {
                if let Some(key) = self.quick_toggle_key {
                    info!(
                        "🎛️ quick-toggle {:?} engaged for smooth local/remote handoff",
                        key
                    );
                }
                self.toggle_grab();
                self.last_quick_toggle_at = Some(now);
            }
        }
        self.quick_toggle_down = quick_toggle_now;
    }

    #[cfg(not(coverage))]
    fn poll_launcher_routing_request(&mut self) {
        let Some(path) = self.routing_control_path.as_deref() else {
            return;
        };
        let Some(raw) = read_launcher_control_snapshot(path) else {
            return;
        };
        if self.last_routing_request_raw.as_deref() == Some(raw.as_str()) {
            return;
        }
        self.last_routing_request_raw = Some(raw.clone());
        let Some(remote_capture) = parse_launcher_routing_request(&raw) else {
            return;
        };
        if self.pending_kill {
            return;
        }
        if remote_capture {
            if !self.released && !self.pending_release {
                return;
            }
            info!("🎛️ launcher requested remote input capture");
            self.enable_remote_capture();
            self.publish_routing_state_if_changed();
        } else {
            if self.released && !self.pending_release {
                return;
            }
            info!("🎛️ launcher requested local input capture");
            self.begin_local_release();
        }
    }

    #[cfg(not(coverage))]
    fn poll_launcher_quick_toggle_request(&mut self) {
        let Some(path) = self.quick_toggle_control_path.as_deref() else {
            return;
        };
        let Some(raw) = read_launcher_control_snapshot(path) else {
            return;
        };
        if self.last_quick_toggle_request_raw.as_deref() == Some(raw.as_str()) {
            return;
        }
        self.last_quick_toggle_request_raw = Some(raw.clone());
        let next_key = raw
            .split_ascii_whitespace()
            .next()
            .and_then(parse_quick_toggle_key);
        self.quick_toggle_key = next_key;
        self.quick_toggle_down = false;
        self.last_quick_toggle_at = None;
        match next_key {
            Some(key) => info!("🎛️ launcher updated the live swap key to {:?}", key),
            None => info!("🎛️ launcher disabled the live swap key"),
        }
    }

    #[cfg(not(coverage))]
    fn poll_launcher_clipboard_request(&mut self) {
        let Some(path) = self.clipboard_control_path.as_deref() else {
            return;
        };
        let marker = path_marker(path);
        if marker <= self.clipboard_control_marker {
            return;
        }
        self.clipboard_control_marker = marker;
        let Some(keyboard) = self.keyboards.first_mut() else {
            warn!("📋 launcher requested clipboard paste, but no keyboard is available");
            return;
        };
        info!("📋 launcher requested clipboard paste on the live relay session");
        keyboard.trigger_clipboard_paste();
        self.record_hid_relayed();
    }

    #[cfg(not(coverage))]
    fn poll_launcher_wake_request(&mut self) {
        let Some(path) = self.wake_control_path.as_deref() else {
            return;
        };
        let Some(raw) = read_launcher_control_snapshot(path) else {
            return;
        };
        if self.last_wake_request_raw.as_deref() == Some(raw.as_str()) {
            return;
        }
        self.last_wake_request_raw = Some(raw.clone());
        self.wake_interval = parse_wake_interval(&raw);
        self.last_hid_relayed_at = Instant::now();
        match self.wake_interval {
            Some(interval) => info!(
                "🛎️ launcher armed Wake after {} minutes without relayed HID input",
                interval.as_secs() / 60
            ),
            None => info!("🛎️ launcher disabled Wake"),
        }
    }

    #[cfg(not(coverage))]
    fn record_hid_relayed(&mut self) {
        self.last_hid_relayed_at = Instant::now();
    }

    #[cfg(coverage)]
    fn record_hid_relayed(&mut self) {
        self.last_hid_relayed_at = Instant::now();
    }

    #[cfg(not(coverage))]
    fn maybe_send_wake_nudge(&mut self) {
        let Some(interval) = self.wake_interval else {
            return;
        };
        if !self.remote_capture_active() || self.last_hid_relayed_at.elapsed() < interval {
            return;
        }
        let (dx, dy) = self.next_wake_delta();
        let nudge = [0, dx as u8, dy as u8, 0];
        let _ = self.mou_tx.send(MouseReport {
            data: nudge.to_vec(),
        });
        let _ = self.mou_tx.send(MouseReport { data: [0; 4].into() });
        self.record_hid_relayed();
        info!(
            "🛎️ Wake sent synthetic mouse nudge dx={} dy={} after {} minutes of quiet HID relay",
            dx,
            dy,
            interval.as_secs() / 60
        );
    }

    #[cfg(not(coverage))]
    fn next_wake_delta(&mut self) -> (i8, i8) {
        self.wake_nonce = self
            .wake_nonce
            .wrapping_mul(6364136223846793005)
            .wrapping_add(1442695040888963407)
            ^ std::time::SystemTime::now()
                .duration_since(std::time::UNIX_EPOCH)
                .map(|duration| duration.as_nanos() as u64)
                .unwrap_or_default();
        let dx = match self.wake_nonce % 5 {
            0 => -2,
            1 => -1,
            2 => 1,
            3 => 2,
            _ => 3,
        };
        self.wake_nonce = self.wake_nonce.rotate_left(17);
        let dy = match self.wake_nonce % 5 {
            0 => -2,
            1 => -1,
            2 => 1,
            3 => 2,
            _ => 3,
        };
        (dx, dy)
    }

    #[cfg(not(coverage))]
    fn publish_routing_state_if_changed(&mut self) {
        let remote_capture = self.remote_capture_active();
        if self.published_remote_capture == Some(remote_capture) {
            return;
        }
        if let Some(path) = self.routing_state_path.as_deref() {
            let _ = std::fs::write(
                path,
                if remote_capture {
                    "remote\n"
                } else {
                    "local\n"
                },
            );
        }
        self.published_remote_capture = Some(remote_capture);
    }

}
