-- factoryos.core.store — persisted named tables.
-- Writes go to `<name>.tmp` then fs.move over the target so a crash mid-write
-- can't leave a torn file. Callers control flush timing.

local M = {}

local dir = "/factoryos/data"

function M.setDir(d) dir = d end

local function path(name) return dir .. "/" .. name .. ".tbl" end

--- Load a store (or default). Returns a plain table — no magic.
function M.load(name, default)
  if fs and fs.exists(path(name)) then
    local h = fs.open(path(name), "r")
    if h then
      local raw = h.readAll()
      h.close()
      local ok, t = pcall(textutils.unserialize, raw)
      if ok and type(t) == "table" then return t end
    end
  end
  return default or {}
end

--- Persist a table atomically-ish. Returns ok, err.
function M.save(name, t)
  if not fs then return false, "no fs" end
  local tmp = path(name) .. ".tmp"
  local ok, h = pcall(fs.open, tmp, "w")
  if not ok or not h then return false, "open failed" end
  h.write(textutils.serialize(t))
  h.close()
  if fs.exists(path(name)) then fs.delete(path(name)) end
  fs.move(tmp, path(name))
  return true
end

return M
