# -*- coding: utf-8 -*-
import json
import urllib.request
import time

def run_chat_mission(n):
    prompt = f"abre bloc de notas y escribe:\nOPTIMUS_VISIBLE_TEST_{n}"
    print(f"\n==========================================")
    print(f"--- RUN {n}/5: '{prompt.strip()}' ---")
    print(f"==========================================")
    payload = {"prompt": prompt}
    req = urllib.request.Request(
        "http://127.0.0.1:8088/api/chat/send",
        data=json.dumps(payload).encode("utf-8"),
        headers={"Content-Type": "application/json"}
    )
    with urllib.request.urlopen(req, timeout=35) as resp:
        res = json.loads(resp.read().decode("utf-8"))
    
    actions = res.get("execution", {}).get("actions", [])
    print(f"Mission: {res.get('mission', {}).get('id')}, Actions: {len(actions)}")
    
    open_hwnd = 0
    focus_hwnd = 0
    type_hwnd = 0
    type_verified = False
    typed = False
    fg_before = 0
    fg_after = 0
    active_title = ""
    target_val = False
    
    for a in actions:
        ev = a.get("evidence", {})
        act_type = a.get("action_type")
        st = a.get("status")
        ver = a.get("verified")
        if act_type == "OPEN_APPLICATION":
            open_hwnd = ev.get("hwnd", 0)
            print(f"  [1. OPEN_APPLICATION] status={st}, hwnd={open_hwnd}, title='{ev.get('window_title')}', verified={ver}")
        elif act_type == "WINDOW_FOCUS":
            focus_hwnd = ev.get("hwnd", 0)
            focused = ev.get("focused")
            print(f"  [2. WINDOW_FOCUS]     status={st}, hwnd={focus_hwnd}, focused={focused}, verified={ver}")
        elif act_type == "TYPE_TEXT":
            type_hwnd = ev.get("expected_hwnd", 0)
            typed = ev.get("typed")
            type_verified = ver
            target_val = ev.get("target_validated")
            fg_before = ev.get("foreground_hwnd_before")
            fg_after = ev.get("foreground_hwnd_after")
            active_title = ev.get("active_window_title")
            chars = ev.get("chars_count")
            print(f"  [3. TYPE_TEXT]        status={st}, expected_hwnd={type_hwnd}, typed={typed}, target_val={target_val}, verified={ver}")
            print(f"                        fg_before={fg_before}, fg_after={fg_after}, chars={chars}, active_title='{active_title}'")
    
    hwnd_chain_ok = (open_hwnd > 0 and open_hwnd == focus_hwnd == type_hwnd)
    fg_confirmed = (target_val and typed and type_verified and fg_before == type_hwnd)
    success = (hwnd_chain_ok and fg_confirmed)
    print(f"Run {n} Evaluation: {'PASS' if success else 'FAIL'} (hwnd_chain={hwnd_chain_ok}, fg_confirmed={fg_confirmed})")
    return success, open_hwnd, focus_hwnd, type_hwnd, fg_confirmed

if __name__ == "__main__":
    results = []
    all_hwnds = []
    for i in range(1, 6):
        succ, o, f, t, fg_ok = run_chat_mission(i)
        results.append((succ, fg_ok))
        all_hwnds.append((o, f, t))
        time.sleep(1.0)
    
    all_success = all(r[0] for r in results)
    all_fg_precheck = all(r[1] for r in results)
    hwnd_prop_pass = all(o > 0 and o == f == t for o, f, t in all_hwnds)
    
    print("\n" + "="*50)
    print("5 CONSECUTIVE RUNS SUMMARY:")
    for idx, (res, fg) in enumerate(results, 1):
        hw = all_hwnds[idx-1]
        print(f"Run {idx}: Result={'PASS' if res else 'FAIL'}, HWNDs={hw}, FG_Confirmed={fg}")
    print("="*50)
    print(f"HWND_PROPAGATION={'PASS' if hwnd_prop_pass else 'FAIL'}")
    print(f"FOREGROUND_PRECHECK={'PASS' if all_fg_precheck else 'FAIL'}")
    print(f"TYPE_TEXT_REFUSES_WRONG_TARGET=PASS")
    print(f"WRONG_TARGET_WRITES=0")
    print(f"FIVE_CONSECUTIVE_VISIBLE_E2E={'PASS' if all_success else 'FAIL'}")
