import time
import pytest
import sys
import os
from unittest.mock import patch

sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), "..")))

from src.api_hook_client import ApiHookClient
from src.markdown_helper import MarkdownRenderer

def _mock_imgui_for_table(mock_imgui):
 mock_imgui.TableFlags_ = type("T", (), {"borders": 1, "row_bg": 2, "resizable": 4})()
 mock_imgui.begin_table.return_value = True
 mock_imgui.table_next_column = lambda: None
 mock_imgui.table_next_row = lambda: None
 mock_imgui.table_headers_row = lambda: None
 mock_imgui.text = lambda *a, **k: None
 mock_imgui.text_wrapped = lambda *a, **k: None
 mock_imgui.end_table = lambda: None
 mock_imgui.same_line = lambda: None
 mock_imgui.spacing = lambda: None
 mock_imgui.indent = lambda *a: None
 mock_imgui.unindent = lambda *a: None

def test_markdown_session_injection_does_not_crash(live_gui) -> None:
 client = ApiHookClient()
 assert client.wait_for_server(timeout=10)
 table_md = "| col1 | col2 |\n| --- | --- |\n| a | b |"
 bullet_md = "- item1\n- item2\n- item3"
 session_entries = [
  {"role": "user", "content": table_md},
  {"role": "user", "content": bullet_md}
 ]
 result = client.post_session(session_entries)
 assert result is not None
 time.sleep(0.5)
 status = client.get_status()
 assert status and "status" in status
 retrieved = client.get_session()
 assert retrieved is not None
 entries = retrieved.get("session", {}).get("entries", [])
 assert len(entries) >= 2

def test_markdown_renderer_runs_on_demand(live_gui) -> None:
 client = ApiHookClient()
 assert client.wait_for_server(timeout=10)
 md_text = (
  "| col1 | col2 |\n| --- | --- |\n| x | y |\n\n"
  "- alpha\n- beta\n- gamma"
 )
 with patch("src.markdown_helper.imgui_md") as mock_md, \
      patch("src.markdown_helper.imgui") as mock_imgui, \
      patch("src.markdown_table.imgui") as mock_table_imgui:
  _mock_imgui_for_table(mock_table_imgui)
  try:
   MarkdownRenderer().render(md_text, context_id="live_md_test")
  except Exception as e:
   pytest.fail(f"MarkdownRenderer.render raised: {e}")
 status = client.get_status()
 assert status and "status" in status
 diag = client.get_gui_diagnostics()
 assert isinstance(diag, dict)
 assert "fps" in diag