import pytest
from unittest.mock import MagicMock, patch
from pathlib import Path
from src import gui_2
from src.gui_2 import App

@pytest.fixture
def mock_config(tmp_path: Path) -> Path:
 config_path = tmp_path / "config.toml"
 config_path.write_text("""[projects]
paths = []
active = ""
[ai]
provider = "gemini"
model = "model"
""", encoding="utf-8")
 return config_path

@pytest.fixture
def mock_project(tmp_path: Path) -> Path:
 project_path = tmp_path / "project.toml"
 project_path.write_text("""[project]
name = "test"
[discussion]
roles = ["User", "AI"]
active = "main"
[discussion.discussions.main]
history = []
""", encoding="utf-8")
 return project_path

@pytest.fixture
def app_instance(mock_config: Path, mock_project: Path, monkeypatch: pytest.MonkeyPatch) -> App:
 monkeypatch.setenv("SLOP_CONFIG", str(mock_config))
 monkeypatch.setattr("src.gui_2.filedialog", MagicMock())
 with patch("src.project_manager.load_project") as mock_load, \
 patch("src.session_logger.open_session"), \
 patch("src.session_logger.reset_session"):
  mock_load.return_value = {
   "project": {"name": "test"},
   "discussion": {"roles": ["User", "AI"], "active": "main", "discussions": {"main": {"history": []}}},
   "files": {"paths": []},
   "screenshots": {"paths": []}
  }
  # Mock the __init__ to do nothing, then set the fields we need manually
  with patch.object(App, '__init__', lambda self: None):
   app = App()
   app.show_windows = {"Log Management": False}
   app.ui_state = MagicMock()
   app.ui_files_base_dir = "."
   app.files = []
   app.controller = MagicMock()
   app.controller.event_queue = MagicMock()
   # Since we bypassed __init__, we need to bind the method manually
   # but python allows calling it directly.
   return app

def test_log_management_init(app_instance: App) -> None:
 app = app_instance
 assert "Log Management" in app.show_windows
 assert app.show_windows["Log Management"] is False
 assert hasattr(gui_2, "render_log_management")
 assert callable(gui_2.render_log_management)

def test_render_log_management_logic(app_instance: App) -> None:
 app = app_instance
 app.show_windows["Log Management"] = True
 # Mock LogRegistry
 with patch("src.log_registry.LogRegistry") as MockRegistry, \
 patch("src.gui_2.imscope") as mock_imscope, \
 patch("src.gui_2.imgui.begin_table") as mock_begin_table, \
 patch("src.gui_2.imgui.text") as mock_text, \
 patch("src.gui_2.imgui.end_table"), \
 patch("src.gui_2.imgui.push_style_color"), \
 patch("src.gui_2.imgui.pop_style_color"), \
 patch("src.gui_2.imgui.table_setup_column"), \
 patch("src.gui_2.imgui.table_headers_row"), \
 patch("src.gui_2.imgui.table_next_row"), \
 patch("src.gui_2.imgui.table_next_column"), \
 patch("src.gui_2.imgui.same_line"), \
 patch("src.gui_2.imgui.text_colored"), \
 patch("src.gui_2.imgui.separator"), \
 patch("src.gui_2.imgui.button", return_value=False):

  mock_reg = MockRegistry.return_value
  mock_reg.data = {
   "session_1": {
    "start_time": "2023-01-01",
    "whitelisted": False,
    "metadata": {"reason": "test", "size_kb": 10, "message_count": 5}
   }
  }
  app._log_registry = mock_reg
  
  mock_window_cm = MagicMock()
  mock_window_cm.__enter__.return_value = (True, True)
  mock_imscope.window.return_value = mock_window_cm

  mock_begin_table.return_value = True
  gui_2.render_log_management(app)
  mock_imscope.window.assert_called_with("Log Management", app.show_windows["Log Management"])
  mock_begin_table.assert_called()
  mock_text.assert_any_call("session_1")

