# -*- coding: utf-8 -*-
"""Persistent Frida trace session (avoids CLI exit on piped stdin)."""
import sys
import time
from datetime import datetime
from pathlib import Path

import frida

PKG = "ph.seabank.seabank"
HERE = Path(__file__).resolve().parent
LOGS_DIR = HERE.parent / "logs" / "frida"
LOGS_DIR.mkdir(parents=True, exist_ok=True)
SCRIPT = HERE / "trace_maribank_register.js"
LOG = LOGS_DIR / ("trace_%s.log" % datetime.now().strftime("%Y%m%d_%H%M%S"))


def on_message(message, data):
    if message.get("type") == "send":
        line = message.get("payload")
    else:
        line = str(message)
    text = line if isinstance(line, str) else repr(line)
    print(text, flush=True)
    with open(LOG, "a", encoding="utf-8") as f:
        f.write(text + "\n")
    if message.get("type") == "error":
        err_log = str(LOG) + ".err"
        with open(err_log, "a", encoding="utf-8") as f:
            f.write(text + "\n")


def wait_for_process(device, pkg, timeout_sec=30):
    deadline = time.time() + timeout_sec
    while time.time() < deadline:
        for app in device.enumerate_applications():
            if app.identifier == pkg and app.pid and app.pid > 0:
                return app.pid
        for proc in device.enumerate_processes():
            if proc.name == pkg:
                return proc.pid
            params = getattr(proc, "parameters", None) or {}
            if params.get("identifier") == pkg:
                return proc.pid
        time.sleep(0.5)
    return None


def launch_app(pkg):
    import subprocess
    adb = r"C:\Users\Administrator\AppData\Local\Android\Sdk\platform-tools\adb.exe"
    subprocess.run(
        [adb, "shell", "am", "force-stop", pkg],
        check=False,
        capture_output=True,
    )
    time.sleep(1)
    subprocess.run(
        [adb, "shell", "monkey", "-p", pkg, "-c", "android.intent.category.LAUNCHER", "1"],
        check=False,
        capture_output=True,
    )


def ensure_frida_server():
    import subprocess
    adb = r"C:\Users\Administrator\AppData\Local\Android\Sdk\platform-tools\adb.exe"
    out = subprocess.run(
        [adb, "shell", "su", "-c", "pgrep frida-server"],
        capture_output=True,
        text=True,
    )
    if out.stdout.strip():
        return
    subprocess.run(
        [adb, "shell", "su", "-c", "/data/local/tmp/frida-server -D &"],
        check=False,
        capture_output=True,
    )
    time.sleep(2)


def main():
    mode = "attach"
    if len(sys.argv) > 1:
        mode = sys.argv[1]

    ensure_frida_server()
    device = frida.get_usb_device(timeout=10)
    source = SCRIPT.read_text(encoding="utf-8")

    pid = None
    if mode == "spawn":
        print("Spawning %s ..." % PKG)
        pid = device.spawn([PKG])
        session = device.attach(pid)
    else:
        print("Attaching %s ..." % PKG)
        pid = wait_for_process(device, PKG, 3)
        if pid is None:
            print("Launching MariBank ...")
            launch_app(PKG)
            pid = wait_for_process(device, PKG, 60)
        if pid is None:
            raise SystemExit("MariBank not running after 60s — open app manually and re-run attach")
        print("Found pid=%s" % pid)
        session = device.attach(pid)

    script = session.create_script(source)
    script.on("message", on_message)
    script.load()

    if mode == "spawn":
        device.resume(pid)
        print("Resumed pid=%s, waiting for JVM..." % pid)
        time.sleep(10)
    else:
        print("Attached pid=%s" % pid)
        time.sleep(3)

    print("Trace running. Log: %s" % LOG)
    print("操作: Sign up -> 输入号码 -> Next (Ctrl+C 结束)")
    try:
        while True:
            time.sleep(1)
    except KeyboardInterrupt:
        print("Stopping...")
        session.detach()


if __name__ == "__main__":
    main()
