from unittest.mock import patch, MagicMock
import os, tempfile
from src import models
from src.gui_2 import render_files_and_media

def test_files_rendered_under_directory_grouping(app_instance):
 with tempfile.TemporaryDirectory() as tmp:
  sub = os.path.join(tmp, "sub")
  os.makedirs(sub, exist_ok=True)
  for p in [os.path.join(tmp, "a.py"), os.path.join(tmp, "b.py"), os.path.join(sub, "c.py")]:
   open(p, "w").close()
  app_instance.files = [models.FileItem(path=os.path.join(tmp, "a.py")), models.FileItem(path=os.path.join(tmp, "b.py")), models.FileItem(path=os.path.join(sub, "c.py"))]
  with patch("src.gui_2.imgui") as mock_imgui, patch("src.gui_2.imscope") as mock_imscope, patch("src.gui_2.filedialog") as mock_filedialog, patch("src.gui_2.hide_tk_root", return_value=MagicMock()):
   mock_imgui.collapsing_header.return_value = True
   mock_imgui.TableFlags_ = type("T", (), {"resizable": 1, "borders": 2, "row_bg": 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_imscope.group.return_value.__enter__.return_value = None
   mock_imscope.tree_node_ex.return_value.__enter__.return_value = True
   mock_filedialog.askopenfilenames.return_value = ()
   mock_filedialog.askdirectory.return_value = ""
   try:
    render_files_and_media(app_instance)
   except Exception as e:
    import pytest
    pytest.fail(f"render_files_and_media raised: {e}")
  assert len(app_instance.files) == 3
  assert mock_imscope.tree_node_ex.called, "render_files_and_media should group files under tree_node_ex by directory"
