#!/usr/bin/env python3
"""Launch the app, take timed screenshots via DVT, and report state at the end.

Usage: launch_shot.py <tag> [shot_seconds_csv]
"""
import os, sys, time, json, subprocess, threading

sys.stdout.reconfigure(encoding='utf-8')
import frida

BID = 'vn.gsm.md'
UDID = '2f04999241eb80cae2d8a6176504af07002b86bd'


class Watchdog:
    def __init__(self, secs=200):
        self.deadline = time.time() + secs
        threading.Thread(target=self._loop, daemon=True).start()

    def _loop(self):
        while True:
            time.sleep(0.25)
            if time.time() > self.deadline:
                print('HARD TIMEOUT', flush=True)
                os._exit(3)


def shot(name):
    r = subprocess.run([sys.executable, '-m', 'pymobiledevice3', 'developer', 'dvt',
                        'screenshot', name, '--udid', UDID],
                       capture_output=True, text=True)
    if r.returncode != 0:
        print('shot fail', name, (r.stderr or '')[-160:], flush=True)
    else:
        try:
            print('shot %s %d bytes' % (name, os.path.getsize(name)), flush=True)
        except OSError:
            print('shot %s (missing)' % name, flush=True)


def main():
    tag = sys.argv[1] if len(sys.argv) > 1 else 'b'
    secs = [int(x) for x in (sys.argv[2].split(',') if len(sys.argv) > 2 else ['4', '10', '16', '24'])]
    Watchdog(max(secs) + 120)
    dev = frida.get_device_manager().add_remote_device('127.0.0.1:7777')
    for p in dev.enumerate_processes():
        if p.name == 'Driver':
            print('kill stale', p.pid, flush=True)
            try:
                dev.kill(p.pid)
            except Exception:
                pass
    time.sleep(1.5)
    for i in range(20):
        try:
            pid = dev.spawn([BID])
            print('launched', pid, flush=True)
            break
        except Exception as e:
            m = str(e)
            print(i, 'wait' if 'unlocked' in m else 'ERR ' + m[:100], flush=True)
            time.sleep(2)
    else:
        print('could not launch')
        return
    dev.resume(pid)
    t0 = time.time()
    for s in secs:
        target = t0 + s
        while time.time() < target:
            time.sleep(0.2)
        alive = any(p.pid == pid for p in dev.enumerate_processes())
        shot('shot_%s_%02d.png' % (tag, s))
        print('t=%ds alive=%s' % (s, alive), flush=True)
        if not alive:
            break


if __name__ == '__main__':
    main()
