local args = (function()
  local parser = require('argparse')()
  parser:argument('product', 'product to fetch')
  return parser:parse()
end)()

local function dblist(product)
  local dbset = {
    GlobalStrings = {},
  }
  local datalua = dofile('runtime/' .. product .. '.lua')
  local sqlcfgs = require('wowapi.yaml').parseFile('runtime/sqls.yaml')
  for sql in pairs(datalua.sqls) do
    -- We are fortunate that sqlite complains about missing tables first.
    local sqltext = sqlcfgs[sql].text
    local db = require('wowless.sqlite').open_memory()
    local tables = {}
    while not db:prepare(sqltext) do
      local t = db:errmsg():match('^no such table: (%a+)$')
      if t then
        tables[t] = {}
        assert(db:exec('CREATE TABLE ' .. t .. ' (moo INTEGER)') == 0)
      else
        break
      end
    end
    for tab, idx in pairs(sqlcfgs[sql].config.indexes or {}) do
      assert(tables[tab], ('index on %q for unused table %q'):format(sql, tab))
      tables[tab][idx] = true
    end
    for k, v in pairs(tables) do
      dbset[k] = dbset[k] or {}
      for vk, vv in pairs(v) do
        assert(dbset[k][vk] == nil or dbset[k][vk] == vv)
        dbset[k][vk] = vv
      end
    end
  end
  for k, v in pairs(dbset) do
    local vv = {}
    for vk in pairs(v) do
      table.insert(vv, vk)
    end
    table.sort(vv)
    dbset[k] = vv
  end
  return dbset
end

local u = require('tools.util')
local outfn = 'generated/' .. args.product .. '_dblist.lua'
local out = dblist(args.product)
require('pl.file').write(outfn, u.returntable(out))
