-- factoryos.core.log — leveled logging to term + bounded ring-buffer file.
local M = {}

M.LEVELS = { debug = 1, info = 2, warn = 3, error = 4 }

local level = M.LEVELS.info
local filePath = nil
local ring = {}
local ringMax = 300
local echo = true

function M.setup(opts)
  opts = opts or {}
  if opts.level then level = M.LEVELS[opts.level] or level end
  filePath = opts.file
  ringMax = opts.ringMax or ringMax
  echo = opts.echo ~= false
end

local function stamp()
  if os.epoch and textutils.formatTime then
    return textutils.formatTime((os.epoch("local") / 1000 % 86400) / 3600, true)
  end
  return string.format("%08.2f", os.clock())
end

local function emit(lv, msg)
  local line = string.format("[%s] %-5s %s", stamp(), lv, msg)
  ring[#ring + 1] = line
  if #ring > ringMax then table.remove(ring, 1) end
  if echo then print(line) end
  if filePath and fs then
    local ok, h = pcall(fs.open, filePath, "a")
    if ok and h then h.writeLine(line); h.close() end
  end
end

function M.dump() return ring end

for lv in pairs(M.LEVELS) do
  M[lv] = function(fmt, ...)
    if M.LEVELS[lv] >= level then
      local ok, msg = pcall(string.format, tostring(fmt), ...)
      emit(lv, ok and msg or tostring(fmt))
    end
  end
end

return M
