import os, tempfile, tomli_w
from unittest.mock import patch, MagicMock
from src.gui_2 import render_log_management

def test_log_management_populates_registry_on_first_open(app_instance):
 with tempfile.TemporaryDirectory() as tmp:
  reg_path = os.path.join(tmp, "log_registry.toml")
  tomli_w.dump({"s1": {"start_time": "2026-06-03T10:00:00", "path": "C:/x/s1", "whitelisted": False}}, open(reg_path, "wb"))
  app_instance._log_registry = None
  app_instance.show_windows = {"Log Management": True}
  app_instance.perf_profiling_enabled = False
  with patch("src.gui_2.paths") as mock_paths, \
       patch("src.gui_2.imgui") as mock_imgui, \
       patch("src.gui_2.imscope") as mock_imscope:
   mock_paths.get_logs_dir.return_value = MagicMock()
   mock_paths.get_logs_dir.return_value.__truediv__ = lambda self, x: reg_path
   mock_imgui.collapsing_header = MagicMock(return_value=True)
   mock_imgui.TableFlags_ = type("T", (), {"borders": 1, "row_bg": 2, "resizable": 4})()
   mock_imgui.TableColumnFlags_ = type("C", (), {"width_fixed": 1, "width_stretch": 2})()
   mock_imgui.begin_table.return_value = True
   mock_imgui.button.return_value = False
   mock_imgui.table_next_row = lambda: None
   mock_imgui.table_next_column = lambda: None
   mock_imgui.text = lambda *a, **k: None
   mock_imgui.text_colored = lambda *a, **k: None
   mock_imgui.text_disabled = lambda *a, **k: None
   mock_imgui.end_table = lambda: None
   mock_imscope.window.return_value.__enter__.return_value = (True, True)
   app_instance.cb_load_prior_log = MagicMock()
   app_instance.controller = MagicMock()
   del app_instance.controller._log_registry
   render_log_management(app_instance)
  assert app_instance._log_registry is not None
  assert "s1" in app_instance._log_registry.data, f"Registry should be populated on first open. Got: {list(app_instance._log_registry.data.keys())}"
