"""Reliable emulator control: launch to menu by polling, tap in landscape coords."""
import subprocess, time
from PIL import Image
ADB="/opt/android-sdk/platform-tools/adb"
PKG="se.foglo.svt"
SHOT="/root/ants/_emu.png"
def sh(*a): return subprocess.run([ADB]+list(a),capture_output=True,text=True,timeout=30)
def tap(x,y): sh("shell","input","tap",str(x),str(y))
def screenshot():
    sh("shell","screencap","-p","/sdcard/_e.png"); sh("pull","/sdcard/_e.png",SHOT)
    return Image.open(SHOT).convert("RGB")
def is_green(p): r,g,b=p; return g>140 and g>r+40 and g>b+40
def menu_ready():
    try: return is_green(screenshot().getpixel((700,700)))
    except Exception: return False
def launch_to_menu(timeout=100):
    sh("shell","am","force-stop",PKG); time.sleep(1)
    sh("shell","input","keyevent","3")  # HOME (dismiss any crash dialog)
    time.sleep(1)
    sh("shell","monkey","-p",PKG,"-c","android.intent.category.LAUNCHER","1")
    t0=time.time()
    while time.time()-t0 < timeout:
        time.sleep(3)
        if menu_ready(): return time.time()-t0
    return None
if __name__=="__main__":
    import sys
    n=int(sys.argv[1]) if len(sys.argv)>1 else 3
    for i in range(n):
        t=launch_to_menu()
        print(f"run {i+1}: menu ready in {t:.0f}s" if t else f"run {i+1}: TIMEOUT", flush=True)
