"""confirm_action tests (pytest-qt, offscreen) — PAPER-04's promotion."""

from __future__ import annotations

import pytest

pytest.importorskip("PySide6")
pytest.importorskip("pytestqt")

from PySide6.QtCore import QTimer
from PySide6.QtWidgets import QApplication, QMessageBox, QPushButton

from mgf.brand_qt.widgets import confirm_action

pytestmark = pytest.mark.gui


def _click_when_shown(label: str) -> None:
    """Schedule a click on the modal button carrying ``label``."""

    def attempt() -> None:
        box = QApplication.activeModalWidget()
        if not isinstance(box, QMessageBox):
            QTimer.singleShot(10, attempt)
            return
        for button in box.buttons():
            if isinstance(button, QPushButton) and button.text() == label:
                button.click()
                return
        raise AssertionError(f"no button labelled {label!r} on the confirm box")

    QTimer.singleShot(0, attempt)


def test_choosing_the_verb_returns_true(qtbot) -> None:
    _click_when_shown("Force detach")
    assert (
        confirm_action(
            None,
            title="Force detach",
            text="Detach camera-0 from operator B?",
            action_text="Force detach",
            danger=True,
        )
        is True
    )


def test_cancel_returns_false_and_is_the_default(qtbot) -> None:
    _click_when_shown("Cancel")
    assert (
        confirm_action(
            None,
            title="Force detach",
            text="Detach camera-0 from operator B?",
            action_text="Force detach",
        )
        is False
    )


def test_danger_paints_the_verb_in_the_danger_variant(qtbot) -> None:
    """The destructive verb carries mgfVariant=danger; the calm one doesn't."""
    seen: dict[str, object] = {}

    def capture() -> None:
        box = QApplication.activeModalWidget()
        if not isinstance(box, QMessageBox):
            QTimer.singleShot(10, capture)
            return
        for button in box.buttons():
            if isinstance(button, QPushButton) and button.text() == "Erase":
                seen["variant"] = button.property("mgfVariant")
        box.reject()

    QTimer.singleShot(0, capture)
    confirm_action(None, title="t", text="x", action_text="Erase", danger=True)
    assert seen["variant"] == "danger"
