"""
iphone_control.py — drive an iPhone from your Mac.

The twin of phone_control.py. Same shape, different road: Android talks to
adb, the iPhone talks to WebDriverAgent, a small app you build in Xcode and
leave running on the phone.

Before this works:
  1. Xcode installed, iPhone plugged in and trusted
  2. WebDriverAgent built onto the phone once (see the page)
  3. Open the tunnel, and leave it open:
       tidevice3 -u <udid> wdaproxy -B com.facebook.WebDriverAgentRunner.xctrunner -p 8100

Run it:
  python3 iphone_control.py

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

import wda

SETTINGS = "com.apple.Preferences"
WDA_URL = "http://localhost:8100"


def connect():
    c = wda.Client(WDA_URL)
    c.wait_ready(timeout=20)

    info = c.device_info()
    print(f"connected to {info.get('name')} — iOS {info.get('version')}")
    print(f"screen {c.window_size()[0]} x {c.window_size()[1]}")
    return c


def open_settings(c):
    c.home()
    c.app_start(SETTINGS)

    # label= is the VoiceOver label — the same idea as Android's text=
    if c(label="Wi-Fi").wait(timeout=5.0):
        print("found Wi-Fi")
    else:
        print("no Wi-Fi row — this phone's Settings look different")


def look_around(c):
    """Print every button the phone is showing right now."""
    print("\n--- what is on screen ---")
    for el in c(className="Button").find_elements():
        label = el.label or el.value or ""
        if str(label).strip():
            print(f"  {str(label).strip()}")


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


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