"""
phone_control.py — drive an Android phone from your Mac, over wifi.

Before this works:
  1. On the phone: Developer options -> Wireless debugging -> ON
  2. On the Mac:   adb pair 192.168.x.x:PORT     (pairing code from the phone)
                   adb connect 192.168.x.x:5555
  3. Check it:     adb devices

Run it:
  python3 phone_control.py                  # uses the only connected device
  python3 phone_control.py 192.168.0.51     # or name one

Krueng AI — krueng.ai/control_your_phone.html
"""

import sys
import time

import uiautomator2 as u2

SETTINGS = "com.android.settings"


def connect():
    """Attach to the phone. With no address, uses the only device adb can see."""
    address = sys.argv[1] if len(sys.argv) > 1 else None
    d = u2.connect(address) if address else u2.connect()

    info = d.device_info
    print(f"connected to {info.get('brand')} {info.get('model')} "
          f"— Android {info.get('version')}")
    print(f"screen {d.window_size()[0]} x {d.window_size()[1]}")
    return d


def wake(d):
    """Turn the screen on and swipe the lock screen away."""
    d.screen_on()
    d.unlock()


def open_settings(d):
    """Open Settings and find the search box by what it says, not where it is."""
    d.app_start(SETTINGS, stop=True)

    # .wait() gives the app time to draw. Without it you race the phone.
    if d(textContains="Search").wait(timeout=5.0):
        print("found the search box")
    else:
        print("no search box — this phone's Settings look different")


def type_something(d, words="wifi"):
    """Type into whatever field has focus."""
    d(textContains="Search").click()
    d.send_keys(words)
    time.sleep(1)
    print(f"typed: {words}")


def look_around(d):
    """Print every button the phone is showing right now."""
    print("\n--- what is on screen ---")
    for node in d.xpath('//*[@clickable="true"]').all():
        label = node.text or node.attrib.get("content-desc") or ""
        if label.strip():
            print(f"  {label.strip()}")


def take_a_picture(d, path="phone.png"):
    d.screenshot(path)
    print(f"\nsaved {path}")


def go_home(d):
    d.press("home")


if __name__ == "__main__":
    phone = connect()
    wake(phone)
    open_settings(phone)
    type_something(phone)
    look_around(phone)
    take_a_picture(phone)
    go_home(phone)
    print("\ndone — the phone did all of that on its own.")
