-- factoryos.core.config — load `return {...}` lua config files safely.
local M = {}

--- Load a config file. Returns table or nil,err. Config files are plain Lua
--- returning a table (CC convention); loadfile gets a sandboxed env with no
--- globals beyond safe stdlib.
function M.load(path)
  if not (fs and fs.exists(path)) then return nil, "missing: " .. path end
  local h = fs.open(path, "r")
  if not h then return nil, "unreadable: " .. path end
  local src = h.readAll()
  h.close()
  local env = {
    pairs = pairs, ipairs = ipairs, tostring = tostring, tonumber = tonumber,
    table = table, string = string, math = math, select = select, type = type,
    error = error, pcall = pcall, print = print,
  }
  local fn, err = load(src, "@" .. path, "t", env)
  if not fn then return nil, "parse: " .. tostring(err) end
  local ok, res = pcall(fn)
  if not ok then return nil, "exec: " .. tostring(res) end
  if type(res) ~= "table" then return nil, "config must return a table" end
  return res
end

--- Load config, or defaults when the file is absent. Marks the result with
--- _absent so callers (claim/adopt logic) can distinguish "never configured"
--- from "configured without the flag".
function M.loadOr(path, defaults)
  local c = M.load(path)
  if c then return c end
  local d = defaults or {}
  d._absent = true
  return d
end

return M
