# -*- coding: utf-8 -*-
"""Spawn MariBank with Frida trace and keep session alive."""
import sys
import time
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_live.log"


def on_message(message, data):
    line = ""
    if message.get("type") == "send":
        line = str(message.get("payload", ""))
    elif message.get("type") == "error":
        line = "ERROR: " + str(message.get("stack", message))
    else:
        line = str(message)
    print(line, flush=True)
    with open(str(LOG), "a", encoding="utf-8", errors="replace") as f:
        f.write(line + "\n")


def main():
    LOG.write_text("", encoding="utf-8")
    source = SCRIPT.read_text(encoding="utf-8")
    device = frida.get_usb_device(timeout=10)
    print("device:", device.name, flush=True)
    pid = device.spawn([PKG])
    print("spawned pid", pid, flush=True)
    session = device.attach(pid)
    script = session.create_script(source)
    script.on("message", on_message)
    script.load()
    device.resume(pid)
    print("resumed — 请在手机: Sign up -> 输入号码 -> Next", flush=True)
    print("log:", LOG, flush=True)
    try:
        while True:
            time.sleep(1)
    except KeyboardInterrupt:
        print("detached", flush=True)


if __name__ == "__main__":
    main()
