import pytest
import time
import os
from src.api_hook_client import ApiHookClient

def test_gui_context_preset_save_load(live_gui) -> None:
 """Verify that saving and loading context presets works via the GUI app."""
 client = ApiHookClient()
 assert client.wait_for_server(timeout=15)

 preset_name = "test_gui_preset"
 test_files = ["test.py"]
 test_screenshots = ["test.png"]

 # Switch to Context Composition tab to ensure it's rendered
 client.push_event("select_tab", {"tab": "Context Composition"})
 time.sleep(1.0)

 # Inject context state directly
 client.push_event("custom_callback", {"callback": "set_context_files_for_test", "args": [test_files]})
 client.push_event("custom_callback", {"callback": "set_screenshots_for_test", "args": [test_screenshots]})
 client.push_event("custom_callback", {"callback": "set_ui_attr", "args": ["ui_new_context_preset_name", preset_name]})
 time.sleep(1.0)
 # Trigger validation and saving logic using our custom test hook
 client.push_event("custom_callback", {"callback": "save_context_preset_force", "args": [preset_name]})
 time.sleep(1.5)

 project_data = client.get_project()
 project = project_data.get("project", {})
 presets = project.get("context_presets", {})
 
 assert preset_name in presets, f"Preset '{preset_name}' not found in project context_presets"
 
 preset_entry = presets[preset_name]
 preset_files = [f["path"] if isinstance(f, dict) else str(f) for f in preset_entry.get("files", [])]
 assert preset_files == test_files
 assert preset_entry.get("screenshots", []) == test_screenshots

 # Clear current state
 client.push_event("custom_callback", {"callback": "set_context_files_for_test", "args": [[]]})
 client.push_event("custom_callback", {"callback": "set_screenshots_for_test", "args": [[]]})
 time.sleep(1.0)

 # Load the preset
 client.push_event("custom_callback", {"callback": "load_context_preset", "args": [preset_name]})
 time.sleep(1.0)

 # DEBUG: Print the background process log (binary mode because the
 # GUI process writes Windows console output that isn't valid UTF-8)
 log_path = os.path.join("logs", "sloppy_py_test.log")
 if os.path.exists(log_path):
  with open(log_path, "rb") as f:
   raw = f.read()
   text = raw.decode("utf-8", errors="replace")
   print(f"BACKGROUND LOG:\n{text}")

 context = client.get_context_state()
 loaded_files = [f["path"] if isinstance(f, dict) else str(f) for f in context.get("files", [])]
 assert loaded_files == test_files
 assert context.get("screenshots", []) == test_screenshots

def test_gui_missing_file_identification(live_gui) -> None:
 """Verify that loading a preset correctly populates the UI state and identifies missing files."""
 client = ApiHookClient()
 assert client.wait_for_server(timeout=15)

 preset_name = "missing_preset"
 test_files = ["exists.py", "missing.py"]

 # Create dummy file that exists
 debug = client.get_value("app_debug_info")
 root = debug.get("active_project_root")
 with open(os.path.join(root, "exists.py"), "w") as f:
  f.write("# exists")

 # Setup context state and save preset via test hook
 client.push_event("custom_callback", {"callback": "set_context_files_for_test", "args": [test_files]})
 client.push_event("custom_callback", {"callback": "save_context_preset_force", "args": [preset_name]})
 time.sleep(1.5)
 
 # Clear current state
 client.push_event("custom_callback", {"callback": "set_context_files_for_test", "args": [[]]})
 time.sleep(1.0)
 
 # Load the preset
 client.push_event("custom_callback", {"callback": "load_context_preset", "args": [preset_name]})
 time.sleep(1.0)
 
 # Verify UI state via debug info
 debug = client.get_value("app_debug_info")
 assert "missing.py" in debug["context_files"]
 assert "exists.py" in debug["context_files"]
 assert "missing.py" in debug["missing_files"]
 assert "exists.py" not in debug["missing_files"]
