#!/usr/bin/python3 -I
"""Run Android session and APK tasks as the signed-in desktop user."""
import os
from pathlib import Path
import re
import subprocess
import sys
import time
import shlex

WAY = "/usr/bin/waydroid"

def query(*args, timeout=12):
    result = subprocess.run(args, text=True, errors="replace", capture_output=True, timeout=timeout)
    if result.returncode:
        raise RuntimeError((result.stderr or result.stdout).strip() or f"Command exited with {result.returncode}")
    return result.stdout

def app_ids(text):
    return set(re.findall(r"^packageName:\s*(\S+)\s*$", text, re.M))

def compatible_package(metadata):
    native = re.search(r"^native-code:\s*(.*)$", metadata, re.M)
    if native and not set(shlex.split(native[1])) & {"x86_64", "x86"}:
        raise ValueError("APK_ABI_UNSUPPORTED")

def start():
    status = query(WAY, "status")
    if not re.search(r"Session:\s*RUNNING", status):
        # The start command stays attached for the life of the Android session.
        subprocess.Popen([WAY,"session","start"], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL,
                         stdin=subprocess.DEVNULL, start_new_session=True)
    end = time.monotonic() + 100
    while time.monotonic() < end:
        try:
            if app_ids(query(WAY, "app", "list")):
                return
        except (RuntimeError, subprocess.TimeoutExpired):
            pass  # The binder service starts after the container reports RUNNING.
        time.sleep(2)
    raise RuntimeError("Android did not become ready. Check the container service, GPU and Wayland session.")

def main(args):
    if os.geteuid() == 0 or not os.environ.get("WAYLAND_DISPLAY"):
        raise RuntimeError("Use the installed desktop in a Wayland session under your normal account.")
    if args == ["open"]:
        start()
        query(WAY, "show-full-ui", timeout=60)
    elif args == ["language"]:
        start()
        query(WAY, "app", "launch", "com.android.settings", timeout=60)
    elif len(args) == 2 and args[0] == "install-apk":
        path = Path(args[1]).resolve(strict=True)
        if not path.is_file() or path.suffix.lower() != ".apk":
            raise ValueError("Select a single .apk application file.")
        metadata = query("/usr/bin/aapt","dump","badging",str(path))
        compatible_package(metadata)
        match = re.search(r"^package:\s+name='([^']+)'",metadata,re.M)
        if not match:
            raise ValueError("Could not read the APK package name.")
        package = match[1]
        start()
        if package in app_ids(query(WAY, "app", "list")):
            print("Package already present: " + package, flush=True)
            return
        query(WAY, "app", "install", str(path), timeout=180)
        for _ in range(20):
            if package in app_ids(query(WAY, "app", "list")):
                print("Installed " + package, flush=True)
                return
            time.sleep(1)
        raise RuntimeError("Android did not report this app in its launcher. Check architecture and app compatibility.")
    else:
        raise ValueError("Choose open or install-apk.")

if __name__ == "__main__":
    try:
        main(sys.argv[1:])
    except (OSError, ValueError, RuntimeError, subprocess.SubprocessError) as error:
        print(error, file=sys.stderr)
        sys.exit(1)
