--[[
    Offline retail license file for Analog Signature (Lightroom Classic).
    Customer drops RetailLicense.txt into the .lrplugin bundle root next to Info.lua.

    Key format (single line, UTF-8):
      ASIG-RETAIL-<16_HEX_UPPER>-<2_HEX_CHECKSUM>

    Checksum = sum(byte pairs of payload hex interpreted as bytes) % 251, encoded as two uppercase hex digits.

    Generate keys for customers:
      python3 scripts/generate-retail-license-key.py
]]
local LrPathUtils = import "LrPathUtils"

local M = {}

local function trim(s)
    return (tostring(s or ""):gsub("^%s+", ""):gsub("%s+$", ""))
end

local function readFile(path)
    local fh, err = io.open(path, "r")
    if not fh then
        return nil, err
    end
    local body = fh:read("*a")
    fh:close()
    return body
end

---@param pluginPath string
---@return boolean licensed
---@return string|nil reason
function M.evaluate(pluginPath)
    if type(pluginPath) ~= "string" or pluginPath == "" then
        return false, "invalid_plugin_path"
    end

    local path = LrPathUtils.child(pluginPath, "RetailLicense.txt")
    local body = readFile(path)
    if not body then
        return false, "missing_retail_license_file"
    end

    local key = trim(body:match("^[^\r\n]+"))
    if key == "" then
        return false, "empty_license_file"
    end

    -- Format: ASIG-RETAIL-1234567890ABCDEF-XX
    local payload, checksumStr = key:match("^ASIG%-RETAIL%-([0-9A-F]+)%-([0-9A-F]+)$")
    if not payload or not checksumStr or #payload ~= 16 or #checksumStr ~= 2 then
        return false, "invalid_license_format"
    end

    -- Verify checksum
    local sum = 0
    for i = 1, #payload, 2 do
        local hex = payload:sub(i, i + 1)
        sum = sum + tonumber(hex, 16)
    end
    
    local calculated = string.format("%02X", sum % 251)
    if calculated ~= checksumStr then
        return false, "checksum_mismatch"
    end

    return true, nil
end

return M
