# -*- coding: utf-8 -*-
"""
oracle_run.py — runner cho sig_oracle.js (spawn-gating, KHONG hook, KHONG doc memory).

Cach dung:
  python oracle_run.py <run-id> [--wait=<giay>] [--auto]
    --wait=N : sau khi resume, cho N giay truoc khi bat dau (mac dinh 75)
    --auto   : tu dong chay bo candidate so voi ground-truth xqsig

Yeu cau: iproxy 7777:7777, sysdiagd (frida-server) chay tren iPhone.
Tren iPhone: khi runner bao "DANG CHO", tap icon Driver de mo app (spawn-gate se giu lai).
"""
import frida, sys, os, time, json, datetime, socket

UDID = '2f04999241eb80cae2d8a6176504af07002b86bd'
BUNDLE = 'vn.gsm.md'
JS = r'E:\ios\dump_tool\sig_oracle.js'
OUTDIR = r'E:\ios\dump_tool\runs'

# ------------------------------------------------------------------
# GROUND-TRUTH: cap (URL -> xqsig) that tu log mitm 05:27:50 2026-11-18
GT = {
    'method': 'GET',
    'url': 'https://api-db.vn.gsm-api.net/price/v1/public/surge/heatmap?lat=15.90400695800781&lng=108.3134918212891&vehicle_model=VF5PLUS',
    'xqsig': 'jYa7llVgJDSvYH+n6eNIoQRxVdS7lrGvroZetWRBVSjFDeGlWVB0l4CY8TLLOBF+CUhWRMfblLFmD33S56AeBujf+jPDmLCJVsTML1CK8zkvjm4mHQe9g5MOLD5K3HFwJvUQxgj76OXDbuCQCTS+/7t0XaFdM/w8qY0vpYyoCbeR7RpT9vfRosyCeu4v3aah/Smzl/wp5RYrN7gQS8VVTS+hv6lR827T5H8RQeivDC51K2vL4Y+w4Z7EP9hyBIXfDL04lrxGGOAeanI2uw2FJIsOpM8c7W7jFux6SmFXwfX/7iHFBkhNeVP3RDuL/q0NlIxka4k4jqEOBpOnxStG8txUV0f67o/mcV/kJ/bCMFNN+pCm006NMOa31YDMjg+3DA==',
}
HOST = 'api-db.vn.gsm-api.net'
PATH = '/price/v1/public/surge/heatmap'
QRY = 'lat=15.90400695800781&lng=108.3134918212891&vehicle_model=VF5PLUS'
PATHQ = PATH + '?' + QRY

# bo candidate tham so (a,b,c) de thu
CANDIDATES = [
    (PATHQ, '', ''),
    ('GET', PATHQ, ''),
    (PATHQ, 'GET', ''),
    (PATH, QRY, ''),
    (PATH, '?' + QRY, ''),
    ('GET', PATH, QRY),
    (PATH, QRY, 'GET'),
    (GT['url'], '', ''),
    (HOST, PATHQ, ''),
    (HOST, PATHQ, 'GET'),
    (GT['url'], 'GET', ''),
    ('GET', GT['url'], ''),
    ('GET ' + PATHQ, '', ''),
    (PATHQ, '', 'GET'),
    ('', PATHQ, 'GET'),
    ('', 'GET', PATHQ),
    ('price/v1/public/surge/heatmap?' + QRY, '', ''),
    ('GET', 'price/v1/public/surge/heatmap?' + QRY, ''),
]


def main():
    run_id = sys.argv[1] if len(sys.argv) > 1 else 'oracle'
    wait_s = 75
    auto = '--auto' in sys.argv
    for a in sys.argv:
        if a.startswith('--wait='):
            wait_s = int(a.split('=', 1)[1])
    os.makedirs(OUTDIR, exist_ok=True)
    logfile = os.path.join(OUTDIR, '%s-%s.log' % (run_id, datetime.datetime.now().strftime('%H%M%S')))
    f = open(logfile, 'w', encoding='utf-8', buffering=1)

    def w(line):
        f.write(str(line) + '\n')
        try:
            print(str(line)[:600])
        except Exception:
            pass

    s = socket.socket(); s.settimeout(2)
    try:
        s.connect(('127.0.0.1', 7777)); s.close()
    except Exception as e:
        print('KHONG ket noi 127.0.0.1:7777 — chay iproxy + sysdiagd. Loi: %s' % e)
        sys.exit(1)

    dev = frida.get_device_manager().add_remote_device('127.0.0.1:7777')

    # don instance cu
    try:
        for p in dev.enumerate_processes():
            if p.name == 'Driver':
                w(json.dumps({'ev': 'kill_old_instance', 'pid': p.pid}))
                dev.kill(p.pid)
        time.sleep(1)
    except Exception as e:
        w(json.dumps({'ev': 'kill_old_failed', 'err': str(e)[:200]}))

    state = {'script': None, 'session': None, 'alive': False}

    def on_detached(reason, *a):
        state['alive'] = False
        w(json.dumps({'ev': 'DETACHED', 'reason': reason,
                      'at': datetime.datetime.now().isoformat()}))

    def on_spawn_added(spawn):
        w(json.dumps({'ev': 'spawn_added', 'pid': spawn.pid,
                      'identifier': spawn.identifier,
                      'at': datetime.datetime.now().isoformat()}))
        if spawn.identifier != BUNDLE:
            dev.resume(spawn.pid)
            return
        try:
            session = dev.attach(spawn.pid)
            session.on('detached', on_detached)
            script = session.create_script(open(JS, encoding='utf-8').read())
            script.load()
            state['script'] = script
            state['session'] = session
            state['alive'] = True
            w(json.dumps({'ev': 'oracle_loaded', 'pid': spawn.pid}))
        except Exception as e:
            w(json.dumps({'ev': 'oracle_load_error', 'err': str(e)[:300]}))
        dev.resume(spawn.pid)
        w(json.dumps({'ev': 'resumed', 'pid': spawn.pid,
                      'at': datetime.datetime.now().isoformat()}))

    dev.on('spawn-added', on_spawn_added)
    dev.enable_spawn_gating()
    w(json.dumps({'ev': 'gate_on', 'run': run_id,
                  'at': datetime.datetime.now().isoformat()}))
    print('[*] DANG CHO — hay TAP icon Driver tren iPhone...')

    # cho spawn
    t0 = time.time()
    while state['script'] is None and time.time() - t0 < 120:
        time.sleep(1)
    if state['script'] is None:
        w(json.dumps({'ev': 'no_spawn_timeout'}))
        try: dev.disable_spawn_gating()
        except Exception: pass
        sys.exit(1)

    ex = state['script'].exports_sync

    # cho app on dinh
    w(json.dumps({'ev': 'waiting', 'sec': wait_s}))
    time.sleep(wait_s)

    def safe(fn, *a):
        try:
            return fn(*a)
        except Exception as e:
            return {'err': 'rpc fail: ' + str(e)[:200]}

    w('ping = ' + json.dumps(safe(ex.ping)))

    if auto:
        w('--- AUTO: bo candidate vs ground-truth ---')
        w('info = ' + json.dumps(safe(ex.info)))
        triples = [[a, b, c] for (a, b, c) in CANDIDATES]
        results = safe(ex.sigMany, triples)
        if isinstance(results, dict):
            w('sigMany loi: ' + json.dumps(results))
        else:
            hit = False
            for i, r in enumerate(results):
                a, b, c = CANDIDATES[i]
                label = '(%d) a=%r b=%r c=%r' % (i, a[:60], b[:60], c[:40])
                if isinstance(r, dict) and r.get('out') == GT['xqsig']:
                    w('MATCH!!! ' + label)
                    hit = True
                elif isinstance(r, dict) and 'out' in r:
                    o = r['out'] or ''
                    w('%-14s len=%-4s %s' % (label, len(o), o[:64]))
                else:
                    w('%-14s ERR %s' % (label, json.dumps(r)[:120]))
            w('KET LUAN: ' + ('FOUND MATCH' if hit else 'KHONG co candidate nao khop'))
    else:
        # che do thao: doc lenh stdin
        print('Commands: ping | info | sig <a> <b> <c> (cach bang tab) | quit')
        while state['alive']:
            try:
                line = input('oracle> ').strip()
            except EOFError:
                break
            if not line:
                continue
            if line == 'quit':
                break
            if line == 'ping':
                w('ping = ' + json.dumps(safe(ex.ping)))
            elif line == 'info':
                w('info = ' + json.dumps(safe(ex.info)))
            elif line.startswith('sig '):
                parts = line[4:].split('\t')
                if len(parts) != 3:
                    print('can 3 tham so cach nhau bang TAB')
                    continue
                w('sig = ' + json.dumps(safe(ex.sig, parts[0], parts[1], parts[2]))[:2000])
            else:
                print('lenh khong ro: ' + line)

    w(json.dumps({'ev': 'run_stop', 'at': datetime.datetime.now().isoformat()}))
    try:
        dev.disable_spawn_gating()
    except Exception:
        pass


if __name__ == '__main__':
    main()
