-- Writes tests/drivers/gold/flag_names.lua from a pokegold checkout.
--
--   luajit tools/goldwalk/gen_flags.lua [../pokegold]
--
-- The output is committed so a bot run needs only this repo and a Gold cache;
-- the disassembly is a build-time input, not a runtime one.  Regenerate after
-- pulling pokegold, then run tests/gold_flag_names_test.lua -- it re-derives
-- the same mapping from the cart and fails if pret has renumbered anything.

package.path = "./?.lua;./?/init.lua;" .. package.path

local Flags = dofile("tools/goldwalk/flags.lua")

local ROOT = arg[1] or "../pokegold"
local OUT  = "src/core/gen2/FlagNames.lua"

local events, _  = Flags.parse(ROOT .. "/constants/event_flags.asm")
local engine, _  = Flags.parse(ROOT .. "/constants/engine_flags.asm")

-- Deterministic output: a pairs() order would rewrite the whole file on every
-- run and bury a real renumber in the diff noise.
local function sortedKeys(t)
  local keys = {}
  for k in pairs(t) do keys[#keys + 1] = k end
  table.sort(keys)
  return keys
end

local function emit(fh, name, tbl)
  fh:write(("  %s = {\n"):format(name))
  for _, k in ipairs(sortedKeys(tbl)) do
    fh:write(("    %s = %d,\n"):format(k, tbl[k]))
  end
  fh:write("  },\n")
end

local fh = assert(io.open(OUT, "w"))
fh:write([[
-- Generated by tools/goldwalk/gen_flags.lua from pret/pokegold.  Do not edit.
--
-- EVENT_* / ENGINE_* name -> the numeric id the cart's scripts carry, which is
-- what src/world/gen2/Events.lua and World:engineFlag key on.  Verified against
-- the ROM by tests/gold_flag_names_test.lua.
return {
]])
fh:write(("  source = %q,\n"):format("pret/pokegold constants/{event,engine}_flags.asm"))
emit(fh, "events", events)
emit(fh, "engine", engine)
fh:write("}\n")
fh:close()

local function count(t)
  local n = 0
  for _ in pairs(t) do n = n + 1 end
  return n
end

print(("wrote %s : %d EVENT_*, %d ENGINE_*")
  :format(OUT, count(events), count(engine)))
