import pytest
import time
import sys
import os

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

from src import api_hook_client

@pytest.mark.integration
def test_auto_switch_sim(live_gui):
 client = api_hook_client.ApiHookClient()
 assert client.wait_for_server(timeout=15), "Hook server did not start"
 
 # Reset layout and save a test profile for Tier 3
 client.set_value('show_windows', {'Diagnostics': True})
 client.push_event('custom_callback', {'callback': 'save_workspace_profile', 'args': ['Tier3Profile', 'project']})
 time.sleep(1)
 
 # Reset layout to something else
 client.set_value('show_windows', {'Diagnostics': False})
 
 # Enable auto switch and bind
 client.set_value('ui_auto_switch_layout', True)
 client.set_value('ui_tier_layout_bindings', {'Tier 1': '', 'Tier 2': '', 'Tier 3': 'Tier3Profile', 'Tier 4': ''})
 
 # Send mma_state_update event to trigger Tier 2
 # Since we can't send raw asyncio events easily via ApiHookClient without a dedicated endpoint,
 # we can simulate it by setting the active_tier via the Hook API if it triggers the logic,
 # OR we can just inject an event into the app's event queue via custom_callback.
 
 def trigger_tier(tier):
  # Inject mma_state_update task directly via hook API
  client.push_event("mma_state_update", {"status": "running", "active_tier": tier})
 
 # First Tier 2
 trigger_tier('Tier 2 (Tech Lead)')
 time.sleep(1)
 assert client.get_value('show_windows').get('Diagnostics', False) == False

 # Then Tier 3
 trigger_tier('Tier 3 (Worker): task-1')
 time.sleep(1)
 
 # Verify
 assert client.get_value('show_windows').get('Diagnostics', False) == True
 
 print("Contextual auto-switch simulation PASSED.")
