import urllib.request
import json
import time
import subprocess
import ctypes
import ctypes.wintypes
import sys

sys.stdout.reconfigure(encoding='utf-8')

print("=== STARTING REAL MANUAL E2E TEST ===")

user32 = ctypes.windll.user32
EnumWindowsProc = ctypes.WINFUNCTYPE(ctypes.c_bool, ctypes.wintypes.HWND, ctypes.wintypes.LPARAM)

def get_notepad_windows():
    windows = []
    def cb(hwnd, lparam):
        if user32.IsWindowVisible(hwnd):
            length = user32.GetWindowTextLengthW(hwnd)
            if length > 0:
                buff = ctypes.create_unicode_buffer(length + 1)
                user32.GetWindowTextW(hwnd, buff, length + 1)
                title = buff.value
                if "notepad" in title.lower() or "bloc de notas" in title.lower():
                    windows.append((hwnd, title))
        return True
    user32.EnumWindows(EnumWindowsProc(cb), 0)
    return windows

print(f"Notepad windows before test: {get_notepad_windows()}")

# 1. Send Prompt 1: "abre bloc de notas y escribe:\nOPTIMUS_PHYSICAL_ACTION_TEST"
prompt1 = "abre bloc de notas y escribe:\nOPTIMUS_PHYSICAL_ACTION_TEST"
req_data = json.dumps({"message": prompt1}).encode("utf-8")
req = urllib.request.Request(
    "http://127.0.0.1:8088/api/chat/send",
    data=req_data,
    headers={"Content-Type": "application/json"},
    method="POST"
)

print(f"\n[1] Sending prompt: {repr(prompt1)}")
start_t = time.time()
with urllib.request.urlopen(req, timeout=30.0) as resp:
    res1_raw = resp.read().decode("utf-8")
    res1 = json.loads(res1_raw)

print(f"[1] Response received in {time.time() - start_t:.2f}s:")
print(f"Status: {res1.get('status')}")
print(f"Response: {res1.get('response')}")
print(f"Mission: {res1.get('mission')}")
print(f"Execution: {res1.get('execution')}")

# Check physical windows after Prompt 1
time.sleep(1.0)
np_windows = get_notepad_windows()
print(f"\nPhysical Notepad Windows after test: {np_windows}")

fg_hwnd = user32.GetForegroundWindow()
fg_len = user32.GetWindowTextLengthW(fg_hwnd)
fg_title = ""
if fg_len > 0:
    buff = ctypes.create_unicode_buffer(fg_len + 1)
    user32.GetWindowTextW(fg_hwnd, buff, fg_len + 1)
    fg_title = buff.value
print(f"Active Foreground Window: HWND={fg_hwnd}, Title='{fg_title}'")

# 2. Send Prompt 2: "nunca vi que se abrió bloc de notas verifica"
prompt2 = "nunca vi que se abrió bloc de notas verifica"
req_data2 = json.dumps({"message": prompt2}).encode("utf-8")
req2 = urllib.request.Request(
    "http://127.0.0.1:8088/api/chat/send",
    data=req_data2,
    headers={"Content-Type": "application/json"},
    method="POST"
)

print(f"\n[2] Sending follow-up prompt: {repr(prompt2)}")
start_t = time.time()
with urllib.request.urlopen(req2, timeout=30.0) as resp2:
    res2_raw = resp2.read().decode("utf-8")
    res2 = json.loads(res2_raw)

print(f"[2] Response received in {time.time() - start_t:.2f}s:")
print(f"Status: {res2.get('status')}")
print(f"Response: {res2.get('response')}")
print(f"Mission: {res2.get('mission')}")
print(f"Execution: {res2.get('execution')}")
