import pytest
import time
import os
import sys

# Ensure project root is in path
sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), "..")))

from src.api_hook_client import ApiHookClient
from src.gui_2 import App

@pytest.mark.integration
def test_selectable_label_stability(live_gui) -> None:
 """
 Verifies that the application starts correctly with --enable-test-hooks
 and that the selectable label infrastructure is present and stable.
 """
 client = ApiHookClient()
 assert client.wait_for_server(timeout=20), "Hook server failed to start"

 # 1. Check initial state via diagnostics: is_viewing_prior_session should be False
 diag = client.get_gui_diagnostics()
 # Based on src/api_hooks.py: result["prior"] = _get_app_attr(app, "is_viewing_prior_session", False)
 assert diag.get("prior") is False, "Initial state should not be viewing prior session"

 # 2. Verify _render_selectable_label exists in the App class
 # This satisfies the requirement to check if it exists in the App class.
 assert hasattr(App, '_render_selectable_label'), "App class must have _render_selectable_label method"

 # 3. Check performance to ensure stability
 perf = client.get_performance()
 metrics = perf.get("performance", {})
 # We check if FPS is reported; in some CI environments it might be low but should be > 0 if rendering
 assert "fps" in metrics, "Performance metrics should include FPS"

 # 4. Basic smoke test: set and get a value to ensure GUI thread is responsive
 # ai_response is a known field that is often rendered using selectable labels in various contexts
 client.set_value("ai_response", "Test selectable text stability")
 # Give it a few frames to process the task
 time.sleep(1)
 val = client.get_value("ai_response")
 assert val == "Test selectable text stability", f"Expected 'Test selectable text stability', got '{val}'"

 # 5. Verify prior session indicator specifically via the gettable field
 # prior_session_indicator is mapped to AppController.is_viewing_prior_session
 prior_val = client.get_value("prior_session_indicator")
 assert prior_val is False, "prior_session_indicator field should be False initially"
