import pytest
import time
import os
from pathlib import Path
from src import api_hook_client

@pytest.mark.live
def test_gui_ux_event_routing(live_gui) -> None:
 client = api_hook_client.ApiHookClient()
 client.click("btn_reset")
 time.sleep(2)
 
 assert client.wait_for_server(timeout=15), "Hook server did not start"

 # ---------------------------------------------------------------- Step 1: MMA Stream Verification
 print("[SIM] Testing MMA Stream Routing...")
 client.push_event('mma_stream', {
  'stream_id': 'Tier 2 (Tech Lead)',
  'text': 'Initial thought trace...'
 })
 time.sleep(1)
 
 status = client.get_mma_status()
 assert 'Tier 2 (Tech Lead)' in status['mma_streams']
 print("[SIM] MMA Stream verified.")

 # ---------------------------------------------------------------- Step 2: Global State Routing
 print("[SIM] Testing Global State Routing...")
 usage = {
  'Tier 1': {'input': 10, 'output': 5, 'model': 'gemini-2.5-flash'},
  'Tier 2': {'input': 20, 'output': 10, 'model': 'gemini-2.5-flash'},
  'Tier 3': {'input': 0, 'output': 0, 'model': ''},
  'Tier 4': {'input': 0, 'output': 0, 'model': ''}
 }
 client.push_event('mma_state_update', {
  'status': 'simulating',
  'tier_usage': usage,
  'tickets': []
 })
 # Poll until the new status lands. Without this, a prior test's stale
 # mma_state_update is still in flight and overwrites our 'simulating'.
 for _ in range(40):
  status = client.get_mma_status()
  if status.get('mma_status') == 'simulating':
   break
  time.sleep(0.25)

 assert status.get('mma_status') == 'simulating', f"Expected 'simulating', got '{status.get('mma_status')}'"
 assert status.get('tier_usage', {}).get('Tier 1', {}).get('input') == 10
 print("[SIM] Global state update verified.")

 # ---------------------------------------------------------------- Step 3: Performance Telemetry
 print("[SIM] Testing Performance Telemetry...")
 # We don't push performance, we read it from the App's monitor
 # But we can verify the Hook API exposes it correctly
 perf = client.get_gui_diagnostics()
 fps = perf.get('fps', 0.0)
 total_frames = perf.get('total_frames', 0)
 print(f"[SIM] Current FPS: {fps}, Total Frames: {total_frames}")
 # We accept either a non-zero FPS or a significant frame count as proof of activity
 assert fps >= 5.0 or total_frames > 0, f"Performance stagnation: {fps} FPS, {total_frames} frames"
 print("[SIM] Performance verified.")

@pytest.mark.live
def test_gui_track_creation(live_gui, live_gui_workspace) -> None:
 client = api_hook_client.ApiHookClient()
 client.click("btn_reset")
 time.sleep(2)
 
 assert client.wait_for_server(timeout=15)
 
 print("[SIM] Testing Track Creation via GUI...")
 track_name = f"ux_sim_test_{int(time.time())}"
 client.push_event("custom_callback", {
  "callback": "_cb_create_track",
  "args": ["UX_SIM_TEST", "Test track created by simulation", "feature"]
 })
 
 # Wait for filesystem sync
 time.sleep(3)
 
 # Verify track exists on disk
 # Path is calculated in _cb_create_track: track_id = f"{name.lower().replace(' ', '_')}_{date_suffix}"
 temp_workspace = live_gui_workspace
 tracks_dir = temp_workspace / "conductor" / "tracks"
 assert tracks_dir.exists(), "Tracks directory not found"
 
 found = False
 for d in tracks_dir.iterdir():
  if d.is_dir() and d.name.startswith("ux_sim_test"):
   print(f"[SIM] Verified track directory: {d.name}")
   found = True
   break
   
 assert found, "Track directory starting with ux_sim_test not found."
 print("[SIM] Track creation verified.")
