import pytest
import time
import tomli_w
import os
import json
from pathlib import Path
from src.api_hook_client import ApiHookClient

def test_tool_preset_switching(live_gui, live_gui_workspace):
 client = ApiHookClient()
 
 # Paths for tool presets
 temp_workspace = live_gui_workspace
 global_tool_presets_path = temp_workspace / "tool_presets.toml"
 project_tool_presets_path = temp_workspace / "project_tool_presets.toml"
 manual_slop_path = temp_workspace / "manual_slop.toml"
 
 # Cleanup before test
 if global_tool_presets_path.exists(): global_tool_presets_path.unlink()
 if project_tool_presets_path.exists(): project_tool_presets_path.unlink()
 
 try:
  # Create a global tool preset
  global_tool_presets_path.write_text(tomli_w.dumps({
   "presets": {
    "TestGlobalTools": {
     "categories": {
      "General": {
       "read_file": "auto",
       "run_powershell": "ask"
      }
     }
    }
   }
  }))
  
  # Trigger reload
  client.push_event("custom_callback", {
   "callback": "_refresh_from_project",
   "args": []
  })
  time.sleep(2)
  
  # Select the tool preset
  client.set_value("ui_active_tool_preset", "TestGlobalTools")
  time.sleep(1)
  
  # Verify state
  state = client.get_gui_state()
  assert state["ui_active_tool_preset"] == "TestGlobalTools"
  
  # Test "None" selection
  client.set_value("ui_active_tool_preset", "")
  time.sleep(1)
  state = client.get_gui_state()
  assert not state.get("ui_active_tool_preset")

 finally:
  # Cleanup
  if global_tool_presets_path.exists(): global_tool_presets_path.unlink()
  if project_tool_presets_path.exists(): project_tool_presets_path.unlink()
