#!/usr/bin/env python3
"""
Lightweight helper to run a Monkey script right after installing an APK.

Usage example inside Cursor task/run config:
    python monkey_agent.py \
        --apk /absolute/path/app-debug.apk \
        --package com.example.demo \
        --script /absolute/path/touch.monkey \
        --start-activity com.example.demo/.MainActivity

Typical flow:
1) Wait for device/emulator to be ready.
2) Optionally install the APK.
3) Optionally pre-launch a target Activity or deep link.
4) Push Monkey script and execute: adb shell monkey -p <pkg> --scriptfile ...

Designed for local dev; keep it gated to debug flows.
"""

from __future__ import annotations

import argparse
import pathlib
import sys
import time
from typing import List, Optional

import phone_pilot.android.adb.utils as _adb
from phone_pilot.android.adb.runner import CommandRunner
from phone_pilot.android.touch.monkey import MonkeyRunner


def wait_for_device(device: Optional[str]) -> None:
    """Backward-compatible wrapper. Prefer: adb_utils.wait_for_device()."""
    _adb.wait_for_device(device)


def install_apk(device: Optional[str], apk_path: pathlib.Path) -> None:
    """Install APK on device (replace existing)."""
    CommandRunner.run(_adb.adb_prefix(device) + ["install", "-r", str(apk_path)])


def post_install_wait(seconds: float) -> None:
    """Give the system a little time to finish dexopt/package scans."""
    if seconds > 0:
        print(f"[agent] post-install wait {seconds}s", file=sys.stderr)
        time.sleep(seconds)


def start_activity(device: Optional[str], component: str) -> None:
    """Start an activity component via am start."""
    CommandRunner.run(_adb.adb_prefix(device) + ["shell", "am", "start", "-n", component])


def start_deeplink(device: Optional[str], uri: str) -> None:
    """Start a deep link intent via am start VIEW."""
    CommandRunner.run(
        _adb.adb_prefix(device)
        + ["shell", "am", "start", "-a", "android.intent.action.VIEW", "-d", uri]
    )


def push_script(device: Optional[str], local: pathlib.Path, remote: str) -> None:
    """Backward-compatible wrapper. Prefer: adb_utils.push_script()."""
    _adb.push_script(device, str(local), remote)


def capture_and_pull_screenshot(
    device: Optional[str], remote_path: str, local_path: pathlib.Path
) -> None:
    """Capture screenshot on device and pull to local path."""
    local_path.parent.mkdir(parents=True, exist_ok=True)
    CommandRunner.run(_adb.adb_prefix(device) + ["shell", "screencap", "-p", remote_path])
    CommandRunner.run(_adb.adb_prefix(device) + ["pull", remote_path, str(local_path)])


def build_parser() -> argparse.ArgumentParser:
    """Build CLI argument parser for monkey agent."""
    p = argparse.ArgumentParser(description="Install APK then run Monkey script to reach a page.")
    p.add_argument("--apk", type=str, help="APK path to install (optional).")
    p.add_argument("--package", help="Target app package for Monkey (optional).")
    p.add_argument("--script", required=True, help="Local Monkey script generated by covert_touch.py.")
    p.add_argument(
        "--remote-script",
        default="/data/local/tmp/auto.mks",
        help="Remote path to push the Monkey script (default: /data/local/tmp/auto.mks).",
    )
    p.add_argument("--device", help="ADB device serial (optional).")
    p.add_argument("--throttle", type=int, default=80, help="Monkey throttle in ms (default: 80).")
    p.add_argument("--seed", type=int, default=1234, help="Monkey seed (default: 1234).")
    p.add_argument("--count", type=int, default=1, help="Monkey invocation count (default: 1).")
    p.add_argument(
        "--screenshot",
        type=str,
        default="monkey_screenshot.png",
        help="Local path to save screenshot after monkey run (default: monkey_screenshot.png).",
    )
    p.add_argument(
        "--post-install-wait",
        type=float,
        default=5.0,
        help="Seconds to wait after install to allow package settle (default: 5.0).",
    )
    p.add_argument(
        "--start-activity",
        help="Optional component to pre-launch, e.g. com.example/.MainActivity.",
    )
    p.add_argument("--deeplink", help="Optional deep link URI to pre-launch.")
    return p


def main(argv: Optional[List[str]] = None) -> int:
    """CLI entry point for monkey agent."""
    args = build_parser().parse_args(argv)

    script_path = pathlib.Path(args.script).expanduser().resolve()
    if not script_path.exists():
        print(f"[agent] monkey script not found: {script_path}", file=sys.stderr)
        return 1

    apk_path: Optional[pathlib.Path] = None
    if args.apk:
        apk_path = pathlib.Path(args.apk).expanduser().resolve()
        if not apk_path.exists():
            print(f"[agent] apk not found: {apk_path}", file=sys.stderr)
            return 1

    wait_for_device(args.device)

    if apk_path:
        install_apk(args.device, apk_path)
        post_install_wait(args.post_install_wait)
    else:
        print("[agent] no apk provided; skipping install and continuing with actions", file=sys.stderr)

    if args.start_activity:
        start_activity(args.device, args.start_activity)
        print("[agent] wait 5s after launch before monkey", file=sys.stderr)
        time.sleep(5.0)
    elif args.deeplink:
        start_deeplink(args.device, args.deeplink)
        print("[agent] wait 5s after deep link before monkey", file=sys.stderr)
        time.sleep(5.0)

    push_script(args.device, script_path, args.remote_script)
    MonkeyRunner.run_monkey(
        args.device,
        args.package,
        args.remote_script,
        args.throttle,
        args.seed,
        args.count,
    )
    print("[agent] wait 3s after monkey before screenshot", file=sys.stderr)
    time.sleep(3.0)
    capture_and_pull_screenshot(
        args.device, "/sdcard/monkey_agent.png", pathlib.Path(args.screenshot).expanduser().resolve()
    )
    return 0


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

