import pytest
import time
import sys
import os
from pathlib import Path

# Ensure project root is in path for imports
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_workspace_profiles_restoration(live_gui):
 """
 
  
   Verifies that workspace profiles can save and restore UI state.
   1. Sets a field (ui_separate_tier1) to True.
   2. Saves a workspace profile.
   3. Resets the field to False.
   4. Loads the workspace profile.
   5. Verifies the field is restored to True.
 """
 client = api_hook_client.ApiHookClient()
 assert client.wait_for_server(timeout=20), "Hook server did not start"
 
 # Ensure we are in a clean state
 print("Ensuring clean state (ui_separate_tier1=False)...")
 client.set_value('ui_separate_tier1', False)
 time.sleep(1.0)
 
 # 1. Set a field that is captured in workspace profiles
 print("Setting ui_separate_tier1 to True...")
 client.set_value('ui_separate_tier1', True)
 
 # Wait for settle
 time.sleep(1.0)
 
 # Verify it is set
 val_before = client.get_value('ui_separate_tier1')
 print(f"Value before save: {val_before}")
 assert val_before is True
 
 # 2. Save workspace profile
 print("Saving workspace profile 'test_restore'...")
 # Using push_event to trigger custom_callback
 client.push_event("custom_callback", {
  "callback": "save_workspace_profile", 
  "args": ["test_restore", "project"]
 })
 
 # Wait for save to complete and profiles to reload in the controller
 time.sleep(2.0)
 
 # 3. Change the field
 print("Changing ui_separate_tier1 to False...")
 client.set_value('ui_separate_tier1', False)
 
 # Wait for settle
 time.sleep(1.0)
 
 # Verify it is changed
 val_mid = client.get_value('ui_separate_tier1')
 print(f"Value after change: {val_mid}")
 assert val_mid is False
 
 # 4. Load the profile
 print("Loading workspace profile 'test_restore'...")
 client.push_event("custom_callback", {
  "callback": "load_workspace_profile", 
  "args": ["test_restore"]
 })
 
 # Wait for load to apply
 time.sleep(2.0)
 
 # 5. Verify restoration
 restored_value = client.get_value('ui_separate_tier1')
 print(f"Restored value: {restored_value}")
 assert restored_value is True
 
 print("Workspace profile restoration test PASSED.")