/// Re-applies the compact launcher size after `present()` so persisted window-manager
/// geometry cannot silently reopen the launcher too large for a 1080p desktop.
fn schedule_launcher_window_guard(
    app: &gtk::Application,
    window: &gtk::ApplicationWindow,
    launcher_size: (i32, i32),
) {
    let guard_window = window.clone();
    glib::timeout_add_local_once(Duration::from_millis(120), move || {
        if guard_window.is_maximized() {
            guard_window.unmaximize();
        }
        guard_window.set_default_size(launcher_size.0, launcher_size.1);
        guard_window.queue_allocate();
    });

    let Ok(path) = std::env::var("LESAVKA_LAUNCHER_MEASURE_PATH") else {
        return;
    };
    let measure_window = window.clone();
    let app = app.clone();
    glib::timeout_add_local_once(Duration::from_millis(320), move || {
        write_launcher_measurement(&measure_window, launcher_size, &path);
        if std::env::var("LESAVKA_LAUNCHER_MEASURE_EXIT").ok().as_deref() == Some("1") {
            app.quit();
        }
    });
}

/// Emits a one-shot launcher size snapshot for local verification runs.
fn write_launcher_measurement(
    window: &gtk::ApplicationWindow,
    launcher_size: (i32, i32),
    path: &str,
) {
    let (min_width, natural_width, _, _) = window.measure(gtk::Orientation::Horizontal, -1);
    let (min_height, natural_height, _, _) =
        window.measure(gtk::Orientation::Vertical, launcher_size.0);
    let payload = json!({
        "requested_width": launcher_size.0,
        "requested_height": launcher_size.1,
        "window_width": window.width(),
        "window_height": window.height(),
        "min_width": min_width,
        "natural_width": natural_width,
        "min_height": min_height,
        "natural_height": natural_height,
    });
    let _ = std::fs::write(
        path,
        serde_json::to_string_pretty(&payload).unwrap_or_else(|_| payload.to_string()),
    );
}
