import pytest

from pygui.backend.data.local_settings import LocalSettings
from pygui.backend.data.local_settings_model import LocalSettingsModel


@pytest.fixture
def shared_settings():
    return LocalSettings()


@pytest.fixture
def model(qapp, tmp_path, shared_settings):
    return LocalSettingsModel(shared_settings, tmp_path)


def test_save_mutates_the_shared_instance_in_place(model, shared_settings):
    # This is the bug candidate 1 fixes: DeviceController holds the same
    # LocalSettings object, so a save here must be visible to it without
    # a reload — no throwaway copy, no stale read until restart.
    model.chamberId = "7"
    model.waferReadTimeout = 45000
    model.saveSettings()

    assert shared_settings.chamber_id == "7"
    assert shared_settings.wafer_read_timeout == 45000


def test_save_persists_to_disk_and_reload_round_trips(tmp_path, qapp, shared_settings):
    model = LocalSettingsModel(shared_settings, tmp_path)
    model.chamberId = "9"
    model.waferRetries = 3
    model.saveSettings()

    reloaded_settings = LocalSettings.read_settings(str(tmp_path))
    other_model = LocalSettingsModel(reloaded_settings, tmp_path)
    other_model.loadSettings()

    assert other_model.chamberId == "9"
    assert other_model.waferRetries == 3


def test_revert_restores_last_saved_values(model):
    model.chamberId = "2"
    model.saveSettings()

    model.chamberId = "unsaved-edit"
    assert model.isDirty is True

    model.revertChanges()
    assert model.chamberId == "2"
    assert model.isDirty is False


def test_invalid_chamber_id_blocks_save(model, shared_settings):
    shared_settings.chamber_id = "before"
    model.chamberId = ""
    model.saveSettings()

    assert model.saveStatus.startswith("error:")
    assert shared_settings.chamber_id == "before"  # unsaved, shared instance untouched
