-- Version.lua — single source of truth for the plugin's
-- version string.  Reads Info.lua's VERSION table via
-- dofile and formats as "MAJOR.MINOR.REVISION build BUILD".
--
-- Required by Launcher.lua (log startup stamp, -version
-- flag to helper) and Handlers.lua (getState response field
-- so the browser console self-identifies).  Any new site
-- that wants the build string should require this module
-- rather than re-implementing the dofile + format dance.

local LrPathUtils = import 'LrPathUtils'

local Version = {}

-- Cached on first call.  Info.lua doesn't change during a
-- running plugin session (reloads re-require this module
-- anyway), so caching is safe and avoids the dofile cost
-- on every getState call.
local cached

function Version.string()
    if cached then return cached end
    local ok, info = pcall(dofile,
        LrPathUtils.child(_PLUGIN.path, 'Info.lua'))
    if not ok or not info or not info.VERSION then
        cached = '(unknown)'
        return cached
    end
    local v = info.VERSION
    -- Build date appended in parens when present.  Older
    -- Info.lua tables without the date field still format
    -- cleanly without it.
    if v.date then
        cached = string.format(
            '%d.%d.%d build %d (%s)',
            v.major or 0, v.minor or 0,
            v.revision or 0, v.build or 0, v.date)
    else
        cached = string.format(
            '%d.%d.%d build %d',
            v.major or 0, v.minor or 0,
            v.revision or 0, v.build or 0)
    end
    return cached
end

return Version
