"""GTK AlertDialog confirmation — works on KDE/Wayland where Adw.MessageDialog may be invisible."""

from __future__ import annotations

from typing import Any, Callable


def gtk_alert_dialog_available(gtk_module: Any) -> bool:
    return callable(getattr(gtk_module, "AlertDialog", None))


def present_confirm_alert(
    gtk_module: Any,
    *,
    parent: Any,
    title: str,
    body: str,
    confirm_label: str,
    cancel_label: str,
    on_approve: Callable[[], None],
    on_decline: Callable[[], None] | None = None,
    glib_idle_add: Callable[..., Any] | None = None,
) -> str:
    """
    Present a native GTK AlertDialog for command confirmation.

    Returns:
        ``async`` — dialog shown, callback will fire later
        ``unavailable`` — AlertDialog missing; caller should direct-approve or use another path
    """
    if not gtk_alert_dialog_available(gtk_module):
        return "unavailable"

    alert_cls = gtk_module.AlertDialog
    dialog = alert_cls()
    dialog.set_message(title)
    if body:
        dialog.set_detail(body)
    dialog.set_buttons([cancel_label, confirm_label])
    dialog.set_cancel_button(0)
    dialog.set_default_button(1)

    def _finish(_source: Any, result: Any, *_args: Any) -> None:
        try:
            index = int(dialog.choose_finish(result))
        except Exception:
            if on_decline is not None:
                on_decline()
            return
        if index == 1:
            on_approve()
        elif on_decline is not None:
            on_decline()

    try:
        dialog.choose(parent, None, _finish, None)
    except Exception:
        return "unavailable"
    return "async"
