"""Tests for ApiHookClient.get_gui_health and the /api/gui_health endpoint.

The endpoint exposes the controller's GUI health state (degraded or not)
to tests so they can fail fast with a clear message when the GUI
crashed (e.g. due to an ImGui IM_ASSERT).
"""
import pytest
from unittest.mock import patch
import sys
import os

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

from src.api_hook_client import ApiHookClient


def test_get_gui_health_calls_endpoint() -> None:
 """get_gui_health hits GET /api/gui_health and returns the dict."""
 client = ApiHookClient()
 with patch.object(client, "_make_request") as mock_make:
  mock_make.return_value = {
   "healthy": True,
   "degraded_reason": None,
   "last_assert": None,
   "io_pool_alive": True,
  }
  health = client.get_gui_health()
  assert health == {
   "healthy": True,
   "degraded_reason": None,
   "last_assert": None,
   "io_pool_alive": True,
  }
  mock_make.assert_any_call("GET", "/api/gui_health")


def test_get_gui_health_handles_empty_response() -> None:
 """get_gui_health returns a default healthy dict on empty/invalid response."""
 client = ApiHookClient()
 with patch.object(client, "_make_request") as mock_make:
  mock_make.return_value = None
  health = client.get_gui_health()
  assert health["healthy"] is True
  assert health["degraded_reason"] is None


def test_get_gui_health_reports_degraded_state() -> None:
 """get_gui_health returns degraded=True when the controller has a degraded_reason."""
 client = ApiHookClient()
 with patch.object(client, "_make_request") as mock_make:
  mock_make.return_value = {
   "healthy": False,
   "degraded_reason": "immapp.run raised RuntimeError: IM_ASSERT(Missing End())",
   "last_assert": "Traceback (most recent call last):\n  File immui.cpp\nIM_ASSERT",
   "io_pool_alive": True,
  }
  health = client.get_gui_health()
  assert health["healthy"] is False
  assert "IM_ASSERT" in health["degraded_reason"]
