"""Find the correct Frida API for this version"""
import frida, subprocess, time

out = subprocess.check_output(
    ['tasklist','/FI','IMAGENAME eq AnyDesk.exe','/FO','CSV','/NH'],
    text=True, stderr=subprocess.DEVNULL)
pid = None
for line in out.strip().split('\n'):
    if 'AnyDesk' in line:
        parts = line.strip().strip('"').split('","')
        pid = int(parts[1].strip('"')); break

print(f"PID: {pid}, Frida: {frida.__version__}")
session = frida.attach(pid)

done = False
def on_msg(msg, data):
    global done
    print(f"  {msg.get('payload', msg)}")
    if msg.get('type') == 'send' and msg.get('payload','').startswith('DONE'):
        done = True

# Test with V8
print("\n=== V8 runtime ===")
s = session.create_script("""
// What does Module look like?
send("typeof Module = " + typeof Module);
try { send("Module keys = " + Object.keys(Module).join(", ")); } catch(e) { send("Module keys err: " + e.message); }
try { send("Module.findExportByName = " + typeof Module.findExportByName); } catch(e) { send("err: " + e.message); }

// Try Process approach
send("typeof Process = " + typeof Process);
try { send("Process keys = " + Object.getOwnPropertyNames(Process).join(", ")); } catch(e) { send("Process keys err: " + e.message); }
try {
    var m = Process.getModuleByName("KERNEL32.DLL");
    send("kernel32 = " + m);
    send("kernel32 keys = " + Object.getOwnPropertyNames(m).join(", "));
    send("getExportByName type = " + typeof m.getExportByName);
    if (typeof m.findExportByName === 'function') {
        var a = m.findExportByName("CreateFileW");
        send("findExportByName CreateFileW = " + a);
    }
    if (typeof m.getExportByName === 'function') {
        var b = m.getExportByName("CreateFileW");
        send("getExportByName CreateFileW = " + b);
    }
} catch(e) { send("Process.getModuleByName err: " + e.message); }

// Try the way the recon script did it (which worked)
try {
    var mods = Process.enumerateModules();
    var k32 = null;
    for (var i = 0; i < mods.length; i++) {
        if (mods[i].name === 'KERNEL32.DLL') { k32 = mods[i]; break; }
    }
    if (k32) {
        send("k32 via enumerate = " + k32.name + " @ " + k32.base);
        send("k32 keys = " + Object.getOwnPropertyNames(k32).join(", "));
        var exps = k32.enumerateExports();
        var cf = null;
        for (var j = 0; j < exps.length; j++) {
            if (exps[j].name === 'CreateFileW') { cf = exps[j]; break; }
        }
        if (cf) {
            send("CreateFileW via enumerate = " + cf.address + " type=" + cf.type);
            // Now try Interceptor.attach with this address
            try {
                Interceptor.attach(cf.address, { onEnter: function(a) {} });
                send("INTERCEPTOR ATTACH SUCCESS!");
            } catch(e2) {
                send("Interceptor.attach fail: " + e2.message);
            }
        }
    }
} catch(e) { send("enumerate err: " + e.message); }

send("DONE");
""", runtime='v8')
s.on('message', on_msg)
s.load()
for _ in range(100):
    if done: break
    time.sleep(0.1)
s.unload()

session.detach()
