from unittest.mock import MagicMock, patch
from src.gui_2 import App, render_empty_context_modal

class _StubController:
 def __init__(self):
  self.calls = []
 def _handle_generate_send(self): self.calls.append("generate")
 def _handle_md_only(self): self.calls.append("md_only")
 def shutdown(self): pass

def test_gen_send_empty_context_opens_warning_modal(app_instance):
 app_instance.ui_selected_context_files = set()
 app_instance.show_empty_context_modal = False
 app_instance._pending_generation_action = None
 app_instance._handle_generate_send()
 assert app_instance.show_empty_context_modal is True
 assert app_instance._pending_generation_action == 'generate'

def test_md_only_empty_context_opens_warning_modal(app_instance):
 app_instance.ui_selected_context_files = set()
 app_instance.show_empty_context_modal = False
 app_instance._pending_generation_action = None
 app_instance._handle_md_only()
 assert app_instance.show_empty_context_modal is True
 assert app_instance._pending_generation_action == 'md_only'

def test_proceed_anyway_dispatches_generate(app_instance):
 app_instance.ui_selected_context_files = set()
 app_instance.show_empty_context_modal = False
 app_instance._pending_generation_action = None
 app_instance._handle_generate_send()
 with patch("src.gui_2.imgui") as mock_imgui:
  mock_imgui.open_popup = MagicMock()
  mock_imgui.begin_popup_modal.return_value = (True, True)
  mock_imgui.button.return_value = True
  mock_imgui.WindowFlags_ = type("W", (), {"always_auto_resize": 1})()
  stub_ctrl = _StubController()
  app_instance.controller = stub_ctrl
  render_empty_context_modal(app_instance)
 assert "generate" in stub_ctrl.calls
 assert app_instance._pending_generation_action is None

def test_proceed_anyway_dispatches_md_only(app_instance):
 app_instance.ui_selected_context_files = set()
 app_instance.show_empty_context_modal = False
 app_instance._pending_generation_action = None
 app_instance._handle_md_only()
 with patch("src.gui_2.imgui") as mock_imgui:
  mock_imgui.open_popup = MagicMock()
  mock_imgui.begin_popup_modal.return_value = (True, True)
  mock_imgui.button.return_value = True
  mock_imgui.WindowFlags_ = type("W", (), {"always_auto_resize": 1})()
  stub_ctrl = _StubController()
  app_instance.controller = stub_ctrl
  render_empty_context_modal(app_instance)
 assert "md_only" in stub_ctrl.calls

def test_gen_send_with_context_skips_warning(app_instance):
 app_instance.ui_selected_context_files = {"some_file.py"}
 app_instance._pending_generation_action = None
 stub_ctrl = _StubController()
 stub_ctrl.ui_selected_context_files = app_instance.ui_selected_context_files
 stub_ctrl._pending_generation_action = app_instance._pending_generation_action
 app_instance.controller = stub_ctrl
 app_instance._handle_generate_send()
 assert "generate" in stub_ctrl.calls
 assert app_instance._pending_generation_action is None
