-- Rebuild prefab caches for ALL installed maps, when this script is loaded.
-- There is a bug in BeamNG where sometimes this does not happen before the scenario is loaded.
-- This causes the scenario to load but then fail to find the prefab.

-- This is identical to the "if" condition inside the function with the same name in the `scenario_scenariosLoader` file
local function buildPrefabCache(levelPath, M)
  local cacheTable = {}
  local foundFiles = FS:findFiles(levelPath, "*.prefab\t*.prefab.json", -1, true, false)
  local dir
  local pathScenarioName
  local ext
  for _, prefabPath in ipairs(foundFiles) do
    if string.endswith(prefabPath, ".json") then
      dir, pathScenarioName, ext = path.splitWithoutExt(prefabPath, ".prefab.json")
    else
      dir, pathScenarioName, ext = path.splitWithoutExt(prefabPath, ".prefab")
    end
    pathScenarioName = string.lower(pathScenarioName)
    cacheTable[dir] = cacheTable[dir] or {}
    local internal_dic = cacheTable[dir]
    internal_dic[pathScenarioName] = prefabPath
  end
  M.prefabCache[levelPath] = cacheTable
end

for _, levelPath in ipairs(core_levels.getLevelPaths()) do
  buildPrefabCache(levelPath, scenario_scenariosLoader)
end