# Q7: build the definitive FUT script-API map: script name -> thunk -> service
# vtable slot, by parsing the 24-byte {?, fnptr, name} records the registrar
# FUN_18004a3a0 writes, then joining with the slot each thunk calls.
import re
out = open("/tmp/ghidra_fut/fut_api_map.txt", "w")
P = lambda *a: print(*a, file=out)

c = dec(0x18004a3a0, 300)
# records appear as: <lhs> = FUN_xxxxxxxxx;  <lhs> = "Name";
pairs = re.findall(r'=\s*(FUN_[0-9a-f]+);\s*\n\s*\w+\s*=\s*"([^"]+)"', c)
P("=== registrar records: %d ===" % len(pairs))

SLOT = re.compile(r"\*\(code \*\*\)\(lVar\d+ \+ (0x[0-9a-f]+|\d+)\)")
rows = []
for fnname, script in pairs:
    ent = int(fnname.replace("FUN_", ""), 16)
    body = dec(ent, 60)
    slots = sorted(set(int(s, 16) if s.startswith("0x") else int(s)
                       for s in SLOT.findall(body)))
    nargs = len(re.findall(r"FUN_18019fb[45]0\(", body))
    ret = "FUN_18019fc00(" in body or "FUN_18019fbf0(" in body
    rows.append((slots[0] if slots else -1, script, ent, nargs, ret, body))

P("\n%-34s %-8s %-14s %s" % ("script name", "slot", "thunk", "args ret"))
for slot, script, ent, nargs, ret, _ in sorted(rows):
    P("%-34s %-8s %#-14x %d    %s" % (script, hex(slot) if slot >= 0 else "-", ent,
                                      nargs, "Y" if ret else ""))

P("\n=== thunks with NO service call (pure local/query) ===")
for slot, script, ent, nargs, ret, body in sorted(rows):
    if slot < 0:
        P("--- %s @ %#x ---" % (script, ent))
        P(body)

WANT = ("AddPlayer", "SaveCurrentSquad", "SaveSquad", "RemovePlayer",
        "GetCurrentSquadID", "GetCurrentSquadData", "SetPlayer", "SwapPlayer")
P("\n=== decompiles of the placement/save path ===")
for slot, script, ent, nargs, ret, body in sorted(rows):
    if any(w.lower() in script.lower() for w in WANT):
        P("--- %s  slot=%s @ %#x ---" % (script, hex(slot) if slot >= 0 else "-", ent))
        P(body)
out.close()
print("wrote fut_api_map.txt; records:", len(pairs))
