from types import SimpleNamespace

import soigia.ui as ui_mod


def test_render_context_session_state_uses_global_streamlit_state(monkeypatch):
    fake_state = {"last_action": "Saved note"}
    fake_streamlit = SimpleNamespace(session_state=fake_state)
    fake_renderer = SimpleNamespace(session_state=lambda: {"last_action": "wrong"})

    monkeypatch.setattr(ui_mod, "st", fake_streamlit)

    context = ui_mod.RenderContext(app=ui_mod.App(), st=fake_renderer)

    assert context.session_state is fake_state
    assert context.session_state.get("last_action") == "Saved note"


def test_paginated_table_uses_distinct_widget_and_state_keys(monkeypatch):
    class GuardedState:
        def __init__(self):
            self._data = {}
            self.writes = []

        def get(self, key, default=None):
            return self._data.get(key, default)

        def __setitem__(self, key, value):
            self.writes.append((key, value))
            self._data[key] = value

        def __contains__(self, key):
            return key in self._data

        def __getitem__(self, key):
            return self._data[key]

    class FakeRenderer:
        def __init__(self):
            self.number_input_calls = []
            self.caption_calls = []

        def caption(self, text):
            self.caption_calls.append(text)

        def number_input(self, label, **kwargs):
            self.number_input_calls.append((label, kwargs))
            return kwargs["value"]

        def dataframe(self, *args, **kwargs):
            return None

    guarded_state = GuardedState()
    fake_streamlit = SimpleNamespace(session_state=guarded_state)
    fake_renderer = FakeRenderer()

    monkeypatch.setattr(ui_mod, "st", fake_streamlit)

    table = ui_mod.TableNode(data=[{"id": 1}, {"id": 2}, {"id": 3}], paginate=True, page_size=2)
    table.order = 29
    context = ui_mod.RenderContext(app=ui_mod.App(), st=fake_renderer)

    table.render(context)

    assert fake_renderer.number_input_calls, "expected pagination control to render"
    widget_key = fake_renderer.number_input_calls[0][1]["key"]
    assert widget_key.endswith(":widget")
    assert guarded_state.writes
    assert all(write_key != widget_key for write_key, _ in guarded_state.writes)


def test_table_render_omits_none_height(monkeypatch):
    class FakeRenderer:
        def __init__(self):
            self.dataframe_calls = []

        def dataframe(self, frame, **kwargs):
            self.dataframe_calls.append(kwargs)

    fake_streamlit = SimpleNamespace(session_state={})
    fake_renderer = FakeRenderer()

    monkeypatch.setattr(ui_mod, "st", fake_streamlit)

    table = ui_mod.TableNode(data=[{"id": 1}], height=None)
    context = ui_mod.RenderContext(app=ui_mod.App(), st=fake_renderer)

    table.render(context)

    assert fake_renderer.dataframe_calls
    assert "height" not in fake_renderer.dataframe_calls[0]
