-- Debug log.  Appends to <scratchRoot>/plugin.log, clustered
-- with the rest of the plugin's ephemeral state so the user
-- can inspect or delete everything in one place.  scratchRoot
-- resolves to /tmp/lr-random-pair-generator on macOS and
-- %TEMP%\lr-random-pair-generator on Windows (see Platform.lua).

local LrFileUtils = import 'LrFileUtils'
local LrPathUtils = import 'LrPathUtils'

local Platform = require 'Platform'

local Log = {}
local LOG_DIR = Platform.scratchRoot
local LOG_PATH = LrPathUtils.child(LOG_DIR, 'plugin.log')

local function now() return os.date('%Y-%m-%d %H:%M:%S') end

-- Ensure the log directory exists before opening the file.
-- Log.reset is called from Launcher.start on every menu click,
-- which is a good opportunity to (re)create the dir.  Log.line
-- is resilient to a missing dir — io.open fails, pcall catches,
-- entry is dropped silently.
local function ensureDir()
    LrFileUtils.createAllDirectories(LOG_DIR)
end

function Log.line(tag, msg, data)
    local ok, f = pcall(io.open, LOG_PATH, 'a')
    if not ok or not f then return end
    local extra = ''
    if data ~= nil then extra = ' ' .. tostring(data) end
    f:write(string.format('[%s] [%s] %s%s\n', now(), tag, msg or '', extra))
    f:close()
end

function Log.reset()
    ensureDir()
    local ok, f = pcall(io.open, LOG_PATH, 'w')
    if ok and f then
        f:write(string.format('[%s] [log] reset\n', now()))
        f:close()
    end
end

return Log
