import pytest
from bouquin.markdown_editor import MarkdownEditor
from bouquin.theme import Theme, ThemeConfig, ThemeManager
from bouquin.toolbar import ToolBar
from PySide6.QtWidgets import QWidget


@pytest.fixture
def editor(app, qtbot):
    themes = ThemeManager(app, ThemeConfig(theme=Theme.LIGHT))
    ed = MarkdownEditor(themes)
    qtbot.addWidget(ed)
    ed.show()
    return ed


def test_toolbar_signals_and_styling(qtbot, editor):
    host = QWidget()
    qtbot.addWidget(host)
    host.show()

    tb = ToolBar(parent=host)
    qtbot.addWidget(tb)
    tb.show()

    tb.boldRequested.connect(editor.apply_weight)
    tb.italicRequested.connect(editor.apply_italic)
    tb.strikeRequested.connect(editor.apply_strikethrough)
    tb.codeRequested.connect(lambda: editor.apply_code())
    tb.headingRequested.connect(lambda s: editor.apply_heading(s))
    tb.bulletsRequested.connect(lambda: editor.toggle_bullets())
    tb.numbersRequested.connect(lambda: editor.toggle_numbers())
    tb.checkboxesRequested.connect(lambda: editor.toggle_checkboxes())

    editor.from_markdown("hello")
    editor.selectAll()
    tb.boldRequested.emit()
    tb.italicRequested.emit()
    tb.strikeRequested.emit()
    tb.headingRequested.emit(24)
    assert editor.to_markdown()


def test_style_letter_button_paths(app, qtbot):
    parent = QWidget()
    qtbot.addWidget(parent)
    # Create toolbar
    from bouquin.markdown_editor import MarkdownEditor

    themes = ThemeManager(app, ThemeConfig(theme=Theme.LIGHT))
    ed = MarkdownEditor(themes)
    qtbot.addWidget(ed)
    tb = ToolBar(parent)
    qtbot.addWidget(tb)

    # Action not added to toolbar -> no widget, early return
    from PySide6.QtGui import QAction

    stray = QAction("Stray", tb)
    tb._style_letter_button(stray, "Z")  # should not raise

    # Now add an action to toolbar and style with tooltip
    act = tb.addAction("Temp")
    tb._style_letter_button(act, "T", tooltip="Tip here")
    btn = tb.widgetForAction(act)
    assert btn.toolTip() == "Tip here"
    assert btn.accessibleName() == "Tip here"
