import urllib.request
import json
import time
import subprocess
import hashlib
import sys

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

print("==================================================")
print("DIGITAL OPTIMUS — REAL E2E VERIFICATION SUITE")
print("==================================================")

def post_chat(message: str) -> dict:
    req_data = json.dumps({"message": message}).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"
    )
    with urllib.request.urlopen(req, timeout=30.0) as resp:
        return json.loads(resp.read().decode("utf-8"))

# TEST 1: OPEN NOTEPAD AND TYPE REAL TEXT
print("\n--- TEST 1: OPEN_APPLICATION -> WINDOW_FOCUS -> TYPE_TEXT ---")
prompt1 = "abre bloc de notas y escribe:\nOPTIMUS_PHYSICAL_ACTION_TEST"
print(f"Sending prompt:\n{prompt1}\n")
res1 = post_chat(prompt1)
reply1_text = res1.get("response", {}).get("text", "")
print("Reply 1:")
print(reply1_text)

actions1 = res1.get("execution", {}).get("actions", [])
print(f"\nActions executed count: {len(actions1)}")
for a in actions1:
    print(f"  - [{a.get('capability')}] {a.get('action_type')}: status={a.get('status')}, verified={a.get('verified')}, evidence={a.get('evidence')}")

# Verify Test 1 invariants
types_executed = [a.get("action_type") for a in actions1]
open_app_pass = ("OPEN_APPLICATION" in types_executed and 
                 actions1[0].get("action_type") == "OPEN_APPLICATION" and 
                 actions1[0].get("status") == "SUCCESS" and 
                 actions1[0].get("verified") is True)

window_focus_pass = ("WINDOW_FOCUS" in types_executed and 
                     actions1[1].get("action_type") == "WINDOW_FOCUS" and 
                     actions1[1].get("status") == "SUCCESS" and 
                     actions1[1].get("verified") is True)

type_text_pass = ("TYPE_TEXT" in types_executed and 
                  actions1[2].get("action_type") == "TYPE_TEXT" and 
                  actions1[2].get("status") == "SUCCESS" and 
                  actions1[2].get("verified") is True and 
                  actions1[2].get("payload", {}).get("text") == "OPTIMUS_PHYSICAL_ACTION_TEST")

stale_action_reuse = any("OPTIMUS_KEYBOARD_E2E_OK" in json.dumps(a) for a in actions1) or ("OPTIMUS_KEYBOARD_E2E_OK" in reply1_text)

print(f"\nTEST 1 RESULTS:")
print(f"  OPEN_APPLICATION_PLANNING: {'PASS' if open_app_pass else 'FAIL'}")
print(f"  WINDOW_FOCUS_CHAIN: {'PASS' if window_focus_pass else 'FAIL'}")
print(f"  TYPE_TEXT_AFTER_FOCUS: {'PASS' if type_text_pass else 'FAIL'}")
print(f"  STALE_ACTION_REUSE: {stale_action_reuse}")

# TEST 2: VERIFICATION FOLLOW-UP
print("\n--- TEST 2: VERIFICATION FOLLOW-UP (NO 'I DON'T KNOW') ---")
prompt2 = "nunca vi que se abrió bloc de notas verifica"
print(f"Sending prompt:\n{prompt2}\n")
res2 = post_chat(prompt2)
reply2_text = res2.get("response", {}).get("text", "")
print("Reply 2:")
print(reply2_text)

i_dont_know = "i don't know" in reply2_text.lower() or "no lo sé" in reply2_text.lower()
followup_has_context = ("bloc de notas" in reply2_text.lower() or "notepad" in reply2_text.lower()) and not i_dont_know
print(f"\nTEST 2 RESULTS:")
print(f"  FOLLOWUP_VERIFICATION_CONTEXT: {'PASS' if followup_has_context else 'FAIL'}")
print(f"  I_DONT_KNOW_ON_VERIFICATION_FOLLOWUP: {i_dont_know}")

# TEST 3: NEGATIVE TEST (Artificial app failure)
print("\n--- TEST 3: NEGATIVE TEST (NON-EXISTENT APP) ---")
prompt3 = "abre aplicacion_inexistente_987654 y escribe: texto_que_no_debe_escribirse"
print(f"Sending prompt:\n{prompt3}\n")
res3 = post_chat(prompt3)
reply3_text = res3.get("response", {}).get("text", "")
print("Reply 3:")
print(reply3_text)

actions3 = res3.get("execution", {}).get("actions", [])
print(f"\nActions executed count: {len(actions3)}")
for a in actions3:
    print(f"  - [{a.get('capability')}] {a.get('action_type')}: status={a.get('status')}, verified={a.get('verified')}, error={a.get('error')}")

# In negative test, either open_app failed and subsequent typing was NOT verified/prevented
neg_open_failed = any(a.get("action_type") == "OPEN_APPLICATION" and a.get("status") == "FAILED" for a in actions3)
type_text_executed_in_neg = any(a.get("action_type") == "TYPE_TEXT" and a.get("status") == "SUCCESS" for a in actions3)
neg_test_pass = neg_open_failed and not type_text_executed_in_neg

print(f"\nTEST 3 RESULTS:")
print(f"  NEGATIVE_TEST_APPLICATION_OPEN_FAILED: {'PASS' if neg_open_failed else 'FAIL'}")
print(f"  TYPE_TEXT_PREVENTED: {'PASS' if not type_text_executed_in_neg else 'FAIL'}")

# Clean up notepad
subprocess.run(["taskkill", "/F", "/IM", "notepad.exe"], capture_output=True)

# File hashes
files_to_hash = [
    r"C:\OptimusProjects\Optimus Developer\src\core\effector_runtime.py",
    r"C:\xampp\htdocs\Digital Optimus\artifacts\brain_host\capability_mission_planner.py",
    r"C:\xampp\htdocs\Digital Optimus\artifacts\brain_host\brain_adapter.py"
]

print("\n--- FILE HASHES AFTER MODIFICATION ---")
for fpath in files_to_hash:
    with open(fpath, "rb") as f:
        h = hashlib.sha256(f.read()).hexdigest()
    print(f"{fpath}: {h}")
