import re
import subprocess
import sys
import time
import xml.etree.ElementTree as ET

ADB = ["adb"]


def adb(*args):
    subprocess.run(ADB + list(args), check=False)


def main():
    adb("shell", "am", "force-stop", "my.com.tngdigital.ewallet")
    time.sleep(2)
    adb("shell", "am", "start", "-n", "my.com.tngdigital.ewallet/.ui.SplashActivity")
    time.sleep(16)
    adb("shell", "uiautomator", "dump", "/sdcard/ui_cc.xml")
    xml = subprocess.check_output(
        ADB + ["shell", "cat", "/sdcard/ui_cc.xml"], text=True, errors="ignore")
    root = ET.fromstring(xml)
    target = None
    register_btn = None
    for node in root.iter("node"):
        rid = node.get("resource-id") or ""
        text = node.get("text") or ""
        if "tv_left" in rid or (text.strip().startswith("+") and len(text.strip()) < 8):
            target = node
        if "注册" in text and node.get("clickable") == "true":
            register_btn = node
    if target is None and register_btn is not None:
        bounds = register_btn.get("bounds", "")
        m = re.match(r"\[(\d+),(\d+)\]\[(\d+),(\d+)\]", bounds)
        if m:
            x1, y1, x2, y2 = map(int, m.groups())
            x, y = (x1 + x2) // 2, (y1 + y2) // 2
            print(f"tap register at {x},{y}")
            adb("shell", "input", "tap", str(x), str(y))
            time.sleep(4)
            adb("shell", "uiautomator", "dump", "/sdcard/ui_cc.xml")
            xml = subprocess.check_output(
                ADB + ["shell", "cat", "/sdcard/ui_cc.xml"], text=True, errors="ignore")
            root = ET.fromstring(xml)
            for node in root.iter("node"):
                rid = node.get("resource-id") or ""
                text = node.get("text") or ""
                if "tv_left" in rid or (text.strip().startswith("+") and len(text.strip()) < 8):
                    target = node
                    break
    if target is None:
        for node in root.iter("node"):
            text = node.get("text") or ""
            if "注册" in text or "Register" in text.lower():
                print("login screen text:", text[:40])
        print("ERROR: country code control not found")
        return 1
    bounds = target.get("bounds", "")
    m = re.match(r"\[(\d+),(\d+)\]\[(\d+),(\d+)\]", bounds)
    if not m:
        print("bad bounds", bounds)
        return 1
    x1, y1, x2, y2 = map(int, m.groups())
    x, y = (x1 + x2) // 2, (y1 + y2) // 2
    print(f"tap country {target.get('text','')} at {x},{y}")
    adb("shell", "input", "tap", str(x), str(y))
    time.sleep(3)
    adb("shell", "uiautomator", "dump", "/sdcard/ui_cc2.xml")
    xml2 = subprocess.check_output(
        ADB + ["shell", "cat", "/sdcard/ui_cc2.xml"], text=True, errors="ignore")
    root2 = ET.fromstring(xml2)
    countries = []
    for node in root2.iter("node"):
        text = (node.get("text") or "").strip()
        if "+61" in text or "+86" in text or "Australia" in text or "Malaysia" in text:
            countries.append(text)
    pid = subprocess.check_output(
        ADB + ["shell", "pidof", "my.com.tngdigital.ewallet"], text=True).strip()
    print("pid:", pid or "DEAD")
    print("countries visible:", countries[:8])
    if countries:
        print("OK region picker visible")
        return 0
    print("FAIL region picker empty/black")
    return 1


if __name__ == "__main__":
    sys.exit(main())
