"""Test with _trigger_blink disabled to isolate the jank."""
import os
import sys
import time
import json
import requests
import subprocess
from pathlib import Path

ROOT = Path(os.getcwd())
TS = time.strftime("%Y%m%d_%H%M%S")

# Sitecustomize that wraps _handle_ai_response to disable _trigger_blink
site_dir = ROOT / "tests" / "artifacts" / "sitepkg_noblink"
site_dir.mkdir(parents=True, exist_ok=True)
sitecustomize = site_dir / "sitecustomize.py"
sitecustomize.write_text('''
import sys
# Disable _trigger_blink in _handle_ai_response to isolate the jank
try:
    import src.app_controller as _ac
    _orig = _ac._handle_ai_response
    def _patched(controller, task):
        # Skip _trigger_blink by calling the original logic without that line
        # Just call _handle_ai_response and then unset _trigger_blink
        _orig(controller, task)
        try:
            controller._trigger_blink = False
            controller._autofocus_response_tab = False
            controller._is_blinking = False
            sys.stderr.write("[NOBLINK] disabled _trigger_blink\\n")
            sys.stderr.flush()
        except Exception as e:
            sys.stderr.write(f"[NOBLINK] error: {e}\\n")
            sys.stderr.flush()
    _ac._handle_ai_response = _patched
    sys.stderr.write("[NOBLINK] patched _handle_ai_response\\n")
    sys.stderr.flush()
except Exception as e:
    sys.stderr.write(f"[NOBLINK] patch failed: {e}\\n")
    sys.stderr.flush()
''', encoding="utf-8")
print(f"Created: {sitecustomize}")

SLOPPY = ROOT / "sloppy.py"
env = os.environ.copy()
env["PYTHONPATH"] = str(ROOT.absolute()) + os.pathsep + str(site_dir.absolute())
log_path = ROOT / "logs" / f"sloppy_noblink_{TS}.log"
log_path.parent.mkdir(exist_ok=True)
log_file = open(log_path, "w", encoding="utf-8")

print(f"Spawning {SLOPPY}...")
proc = subprocess.Popen(
    ["uv", "run", "python", "-u", str(SLOPPY), "--enable-test-hooks"],
    stdout=log_file,
    stderr=log_file,
    text=True,
    cwd=str(ROOT.absolute()),
    env=env,
)

print("Waiting for hook server...")
ready = False
start = time.time()
while time.time() - start < 30:
    try:
        r = requests.get("http://127.0.0.1:8999/status", timeout=0.5)
        if r.status_code == 200:
            ready = True
            break
    except: pass
    if proc.poll() is not None:
        print(f"  proc died rc={proc.returncode}")
        break
    time.sleep(0.5)

if not ready:
    print("FAILED to start")
    log_file.close()
    sys.exit(1)

def post(label, payload):
    print(f"POST {label}")
    r = requests.post("http://127.0.0.1:8999/api/gui", json=payload, timeout=5)
    return r

mock_path = (ROOT / "tests" / "mock_gemini_cli.py").absolute()
post("reset", {"action": "click", "item": "btn_reset"})
time.sleep(0.5)
post("provider", {"action": "set_value", "item": "current_provider", "value": "gemini_cli"})
time.sleep(0.5)
post("gcli_path", {"action": "set_value", "item": "gcli_path", "value": f'"{sys.executable}" "{mock_path}"'})
time.sleep(0.5)
post("env", {"action": "custom_callback", "callback": "_set_env_var", "args": ["MOCK_MODE", "malformed_json"]})
time.sleep(0.5)
post("input", {"action": "set_value", "item": "ai_input", "value": "Trigger"})
time.sleep(0.5)
print("CLICK btn_gen_send")
post("gen", {"action": "click", "item": "btn_gen_send"})

print("Polling for response event...")
start = time.time()
event = None
for i in range(30):
    if proc.poll() is not None:
        print(f"  Process died rc={proc.returncode} after {time.time()-start:.2f}s")
        break
    try:
        r = requests.get("http://127.0.0.1:8999/api/events", timeout=5)
        if r.status_code == 200:
            evs = r.json().get("events", [])
            for ev in evs:
                pst = ev.get("payload", {}).get("status", "?")
                txt = ev.get("payload", {}).get("text", "")
                print(f"  Event: type={ev.get('type')} status={pst} text={txt[:200]}")
                if pst != "streaming...":
                    event = ev
            if event: break
    except Exception as e:
        print(f"  HTTP err: {e}")
    time.sleep(1)

print(f"\nFinal event: {event}")
print(f"Final poll: {proc.poll()}")

if proc.poll() is None:
    proc.terminate()
    try: proc.wait(timeout=5)
    except: proc.kill()
log_file.close()

# Print NOBLINK lines
with open(log_path, encoding="utf-8") as f:
    for line in f:
        if "NOBLINK" in line or "cmd_list" in line:
            print(line.rstrip())
