#!/usr/bin/env python3
"""Runtime ObjC introspection of the running Driver app (attach only, no hooks)."""
import os, sys, time, json, threading

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


class Watchdog:
    def __init__(self, secs=60):
        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)


JS = r"""
const out = {};
const names = Object.keys(ObjC.classes);

function interesting(n) {
    return /Driver|AppDelegate|Scene|Shield|Banned|Flutter|BuildInfo|bshield|Root|Main/i.test(n);
}
const picked = names.filter(interesting).sort();
send({type: 'class_count', total: names.length});
send({type: 'classes', list: picked});

// instances of key classes
const counts = {};
for (const cn of ['FlutterEngine', 'FlutterViewController', 'UIWindow', 'UIApplication']) {
    try {
        const k = ObjC.classes[cn];
        if (k) counts[cn] = k.instances ? ObjC.chooseSync(k).length : 'n/a';
    } catch (e) { counts[cn] = 'err'; }
}
send({type: 'instances', counts: counts});

// app delegate + window/root vc state
try {
    const app = ObjC.classes.UIApplication.sharedApplication();
    const del = app.delegate();
    send({type: 'delegate', cls: del ? del.$className : null});
    const win = app.keyWindow ? app.keyWindow() : null;
    send({type: 'window', win: win ? win.toString() : null});
} catch (e) { send({type: 'app_err', err: String(e)}); }

// scene state
try {
    const app = ObjC.classes.UIApplication.sharedApplication();
    const scenes = app.connectedScenes();
    send({type: 'scenes', count: scenes.count()});
    if (scenes.count() > 0) {
        const s = scenes.anyObject();
        const wc = s.windows();
        send({type: 'scene_windows', n: wc.count()});
        for (let i = 0; i < Math.min(wc.count(), 3); i++) {
            const w = wc.objectAtIndex_(i);
            const rvc = w.rootViewController();
            send({type: 'scene_win', i: i, cls: w.$className,
                  hidden: w.isHidden ? w.isHidden() : null,
                  root: rvc ? rvc.$className : null});
        }
    }
} catch (e) { send({type: 'scene_err', err: String(e)}); }
"""


def main():
    Watchdog(60)
    dev = frida.get_device_manager().add_remote_device('127.0.0.1:7777')
    procs = {p.name: p.pid for p in dev.enumerate_processes()}
    pid = procs.get('Driver')
    if not pid:
        print('Driver not running')
        return
    print('attach', pid, flush=True)
    sess = dev.attach(pid)
    s = sess.create_script(JS)
    msgs = []
    s.on('message', lambda m, d: msgs.append(m))
    s.load()
    time.sleep(15)
    sess.detach()

    for m in msgs:
        p = m.get('payload') or {}
        t = p.get('type')
        if t == 'class_count':
            print('total ObjC classes:', p['total'])
        elif t == 'classes':
            print('\n== interesting classes (%d) ==' % len(p['list']))
            for i in range(0, len(p['list']), 3):
                print('  ' + ' | '.join(x.ljust(38) for x in p['list'][i:i + 3]))
        elif t == 'instances':
            print('\n== live instances ==')
            for k, v in p['counts'].items():
                print('  %-24s %s' % (k, v))
        elif t in ('delegate', 'window', 'scenes', 'scene_windows', 'scene_win', 'app_err', 'scene_err'):
            print('\n[%s] %s' % (t, json.dumps({k: v for k, v in p.items() if k != 'type'})))


if __name__ == '__main__':
    main()
