import pytest
import time
import sys
import os

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
@pytest.mark.timeout(120)
def test_patch_modal_appears_on_trigger(live_gui) -> None:
 """
 
  
      Test that triggering a patch shows the modal in the GUI.
      Uses live_gui fixture to start the GUI with test hooks enabled.
 """
 proc, _ = live_gui
 client = api_hook_client.ApiHookClient()
 
 if not client.wait_for_server(timeout=15):
  pytest.skip("GUI server not available")
 
 sample_patch = """--- a/test_file.py
+++ b/test_file.py
@@ -1,3 +1,4 @@
 def hello():
-    print("old")
+    print("new")
+    print("extra")
     return True"""
 
 client.push_event("show_patch_modal", {"patch_text": sample_patch, "file_paths": ["test_file.py"]})
 
 time.sleep(2)
 
 status = client.get_gui_state()
 print(f"[DEBUG] GUI state: {status}")
 assert status.get("_show_patch_modal") == True, f"Patch modal should be visible but got {status}"
 
 client.push_event("hide_patch_modal", {})
 
 time.sleep(1)
 
 status = client.get_gui_state()
 assert status.get("_show_patch_modal") == False, "Patch modal should be closed after hide"

@pytest.mark.integration
@pytest.mark.timeout(120)
def test_patch_apply_modal_workflow(live_gui) -> None:
 """
 
  
      Test the full patch apply workflow: trigger -> apply -> verify modal closes.
 """
 proc, _ = live_gui
 client = api_hook_client.ApiHookClient()
 
 if not client.wait_for_server(timeout=15):
  pytest.skip("GUI server not available")
 
 sample_patch = """--- a/example.py
+++ b/example.py
@@ -5,3 +5,4 @@
 def calculate():
     x = 1
-    return x
+    return x + 1
+    # added line"""
 
 client.push_event("show_patch_modal", {"patch_text": sample_patch, "file_paths": ["example.py"]})

 time.sleep(2)

 status = client.get_gui_state()
 assert status.get("_show_patch_modal") == True, f"Modal should be visible: {status}"

 client.push_event("hide_patch_modal", {})
 time.sleep(1)

 status = client.get_gui_state()
 assert status.get("_show_patch_modal") == False, "Patch modal should close after hide"