from __future__ import annotations

import sys
from pathlib import Path

sys.path.insert(0, str(Path(__file__).resolve().parents[1]))

from ui.settings_dialog import SettingsDialog, _FallbackGtk
from ui.settings_store import Settings


def _dialog(
    settings: Settings, saved: list[Settings]
) -> SettingsDialog:
    return SettingsDialog(settings, saved.append, gtk_module=_FallbackGtk)


def test_controls_reflect_settings() -> None:
    dialog = _dialog(
        Settings(
            auto_close=True,
            refresh_interval_seconds=120,
            warning_threshold_pct=25,
            last_tab="grok",
            theme="dark",
        ),
        [],
    )
    assert dialog.auto_close_switch.get_active() is True
    assert dialog.refresh_spin.get_value() == 120
    assert dialog.threshold_spin.get_value() == 25
    assert dialog.theme_combo.get_active_id() == "dark"
    assert dialog.saved is None


def test_save_calls_on_save_with_new_values_and_preserves_last_tab() -> None:
    saved: list[Settings] = []
    dialog = _dialog(Settings(last_tab="claude"), saved)
    dialog.simulate_save(
        Settings(
            auto_close=True,
            refresh_interval_seconds=300,
            warning_threshold_pct=10,
            last_tab="IGNORED",
            theme="light",
        )
    )
    expected = Settings(
        auto_close=True,
        refresh_interval_seconds=300,
        warning_threshold_pct=10,
        last_tab="claude",
        theme="light",
    )
    assert saved == [expected]
    assert dialog.saved == expected


def test_theme_defaults_to_system() -> None:
    dialog = _dialog(Settings(), [])
    assert dialog.theme_combo.get_active_id() == "system"


def test_spin_controls_clamp_to_spec_ranges() -> None:
    saved: list[Settings] = []
    dialog = _dialog(Settings(), saved)
    dialog.simulate_save(
        Settings(refresh_interval_seconds=999_999, warning_threshold_pct=1)
    )
    assert saved[-1].refresh_interval_seconds == 3600
    dialog.refresh_spin.set_value(1)
    dialog.threshold_spin.set_value(99)
    assert dialog.refresh_spin.get_value() == 30
    assert dialog.threshold_spin.get_value() == 50


def test_cancel_does_not_call_on_save() -> None:
    saved: list[Settings] = []
    dialog = _dialog(Settings(auto_close=True), saved)
    dialog.open()
    assert saved == []
    assert dialog.saved is None
    assert dialog.dialog.destroyed is True


def test_dialog_is_modal_with_cancel_and_save_buttons() -> None:
    dialog = _dialog(Settings(), [])
    assert dialog.dialog.title == "Settings"
    assert dialog.dialog.modal is True
    assert dialog.dialog.buttons == [
        ("Cancel", _FallbackGtk.ResponseType.CANCEL),
        ("Save", _FallbackGtk.ResponseType.OK),
    ]


def test_dialog_constructs_headless_without_gtk_module() -> None:
    dialog = SettingsDialog(Settings(), lambda _settings: None)
    assert dialog.auto_close_switch is not None
