import pytest
import time
from src import api_hook_client

@pytest.mark.live
@pytest.mark.clean_baseline
def test_visual_mma_components(live_gui):
 client = api_hook_client.ApiHookClient()
 client.click("btn_reset")
 time.sleep(2)

 assert client.wait_for_server(timeout=15)

 # 1. Inject MMA State
 usage = {
  'Tier 1': {'input': 100, 'output': 50, 'model': 'gemini-3.1-pro-preview'},
  'Tier 2': {'input': 200, 'output': 100, 'model': 'gemini-3.1-flash-lite'},
  'Tier 3': {'input': 300, 'output': 150, 'model': 'gemini-3.1-flash-lite'},
  'Tier 4': {'input': 400, 'output': 200, 'model': 'gemini-3.1-flash-lite'}
 }

 client.push_event('mma_state_update', {
  'status': 'running',
  'tier_usage': usage,
  'active_tier': 'Tier 2 (Tech Lead)',
  'tickets': []
 })

 # Poll until the push_event task is processed. Without this, the
 # assertion fires BEFORE the active_tier setter runs in the GUI
 # render loop (race condition surfaced in batched live_gui context).
 for _ in range(40):
  status = client.get_mma_status()
  if status.get('active_tier') == 'Tier 2 (Tech Lead)':
   break
  time.sleep(0.25)

 # Verify initial injection
 status = client.get_mma_status()
 assert status['mma_status'] == 'running'
 assert status['active_tier'] == 'Tier 2 (Tech Lead)'

 # 2. Verify Tiered Visibility Logic
 # Set focused tier to Tier 3
 client.set_value('ui_focus_agent', 'Tier 3 (Worker)')

 # Poll until the focus setter lands
 for _ in range(40):
  state = client.get_gui_state()
  if state.get('ui_focus_agent') == 'Tier 3 (Worker)':
   break
  time.sleep(0.25)

 # Verify focused tier
 state = client.get_gui_state()
 assert state.get('ui_focus_agent') == 'Tier 3 (Worker)'

 # 3. Test Progress Indicators
 # Increment progress
 client.push_event('mma_state_update', {
  'status': 'running',
  'tier_usage': usage,
  'active_tier': 'Tier 3 (Worker): task-1',
  'tickets': [{'id': 'task-1', 'title': 'Task 1', 'status': 'in_progress', 'progress': 0.5}]
 })

 # Poll until the new active_tier is visible
 for _ in range(40):
  status = client.get_mma_status()
  if status.get('active_tier') == 'Tier 3 (Worker): task-1':
   break
  time.sleep(0.25)

 # Verify state updated to Tier 3
 status = client.get_mma_status()
 assert status['active_tier'] == 'Tier 3 (Worker): task-1'

 # 4. Test Completion
 client.push_event('mma_state_update', {
  'status': 'idle',
  'tier_usage': usage,
  'active_tier': None,
  'tickets': [{'id': 'task-1', 'title': 'Task 1', 'status': 'completed', 'progress': 1.0}]
 })

 # Poll until mma_status becomes 'idle'
 for _ in range(40):
  status = client.get_mma_status()
  if status.get('mma_status') == 'idle':
   break
  time.sleep(0.25)

 status = client.get_mma_status()
 assert status['mma_status'] == 'idle'
 assert status['active_tier'] is None
