-- Versioned, checksummed packages for offline shared-profile transfer.

local EnsureApiRegistry = rawget(_G, "LIDCOUNCIL_EnsureApiRegistry")
local API, INTERNAL_API
if type(EnsureApiRegistry) == "function" then
  API, INTERNAL_API = EnsureApiRegistry()
else
  API = rawget(_G, "LIDCOUNCIL_API")
  if type(API) ~= "table" then
    API = {}
    _G.LIDCOUNCIL_API = API
  end
  if type(API.__internal) ~= "table" then
    API.__internal = {}
  end
  INTERNAL_API = API.__internal
end

local Package = {}
local PACKAGE_PREFIX = "LIDPKG1:"
local PACKAGE_KIND = "SHARED_PROFILE_PACKAGE"
local PACKAGE_VERSION = 1
local DEFAULT_PART_SIZE = 60000
local MIN_PART_SIZE = 4000
local MAX_PART_SIZE = 500000
local MAX_HEADER_SIZE = 16384
local MAX_RECOVERY_BACKUPS = 3

local SCOPE_ORDER = {
  "full_profile",
  "profile_setup",
  "roles_rights",
  "loot_list",
  "item_history",
  "session_history",
  "fun_awards",
}

local SCOPE_ALIASES = {
  full = "full_profile",
  profile = "full_profile",
  settings = "profile_setup",
  permissions = "roles_rights",
  rights = "roles_rights",
  loot = "loot_list",
  items = "item_history",
  sessions = "session_history",
  awards = "fun_awards",
}

local SCOPE_DEFS = {
  full_profile = {
    key = "full_profile",
    label = "Complete Shared Profile",
    description = "Every shared profile section in one package.",
    payloadKind = "full",
    replacement = "exact",
  },
  profile_setup = {
    key = "profile_setup",
    label = "Profile Setup",
    description = "Raid setup, profile image, roll options, and point configuration.",
    payloadKind = "domain",
    domains = { "settings" },
    replacement = "exact",
  },
  roles_rights = {
    key = "roles_rights",
    label = "Roles & Rights",
    description = "Profile members, roles, and the role-rights policy.",
    payloadKind = "domain",
    domains = { "permissions" },
    replacement = "exact",
  },
  loot_list = {
    key = "loot_list",
    label = "Loot List and Character Details",
    description = "Characters, links, notes, awarded items, manual adjustments, and groups.",
    payloadKind = "subdomain",
    authoritativeArchiveScope = "LOOT_LIST",
    replacement = "authoritative",
  },
  item_history = {
    key = "item_history",
    label = "Item History",
    description = "Live Board item, assignment, and trade history.",
    payloadKind = "subdomain",
    subdomains = { "session_live_board" },
    replacement = "exact",
  },
  session_history = {
    key = "session_history",
    label = "Session History",
    description = "Completed and retained session records.",
    payloadKind = "subdomain",
    authoritativeArchiveScope = "SESSION_HISTORY",
    replacement = "authoritative",
  },
  fun_awards = {
    key = "fun_awards",
    label = "Fun Award Events",
    description = "Canonical real roll and council-vote events used to rebuild Fun Awards.",
    payloadKind = "subdomain",
    authoritativeArchiveScope = "FUN_AWARDS",
    replacement = "authoritative",
    dependencies = { "loot_list" },
    dependencyMode = "recommended",
  },
}

function Package.Trim(value)
  local text = tostring(value or "")
  text = text:gsub("^%s+", "")
  text = text:gsub("%s+$", "")
  return text
end

function Package.Copy(value, seen)
  if type(value) ~= "table" then
    return value
  end
  seen = type(seen) == "table" and seen or {}
  if seen[value] then
    return seen[value]
  end
  local result = {}
  seen[value] = result
  for key, entry in pairs(value) do
    result[Package.Copy(key, seen)] = Package.Copy(entry, seen)
  end
  return result
end

function Package.Checksum(deps, value)
  if type(deps) == "table" and type(deps.CalculateStableChecksum) == "function" then
    local ok, checksum = pcall(deps.CalculateStableChecksum, value)
    if ok and Package.Trim(checksum) ~= "" then
      return Package.Trim(checksum)
    end
  end
  local text = tostring(value or "")
  local hash = 5381
  for index = 1, #text do
    hash = (hash * 33 + string.byte(text, index)) % 4294967291
  end
  return string.format("%08x", hash)
end

function Package.Escape(value)
  return (tostring(value or ""):gsub("([^%w%-%._])", function(character)
    return string.format("%%%02X", string.byte(character))
  end))
end

function Package.Unescape(value)
  local encoded = tostring(value or "")
  local residual = encoded:gsub("%%[%x][%x]", "")
  if residual:find("%", 1, true) then
    return nil, "Malformed package metadata escape."
  end
  return (encoded:gsub("%%(%x%x)", function(hex)
    return string.char(tonumber(hex, 16))
  end))
end

function Package.SplitCsv(value)
  local result = {}
  for token in tostring(value or ""):gmatch("[^,]+") do
    local resolved = Package.Trim(token)
    if resolved ~= "" then
      result[#result + 1] = resolved
    end
  end
  return result
end

function Package.JoinCsv(values)
  local result = {}
  for _, value in ipairs(type(values) == "table" and values or {}) do
    result[#result + 1] = Package.Trim(value)
  end
  return table.concat(result, ",")
end

function Package.NormalizeScopes(requested)
  local source = {}
  if type(requested) == "string" then
    source = Package.SplitCsv(requested)
  elseif type(requested) == "table" then
    source = requested
  end
  local selected = {}
  local unknown = {}
  for _, value in ipairs(source) do
    local key = string.lower(Package.Trim(value)):gsub("[%s%-]+", "_")
    key = SCOPE_ALIASES[key] or key
    if SCOPE_DEFS[key] then
      selected[key] = true
    elseif key ~= "" then
      unknown[#unknown + 1] = key
    end
  end
  if #unknown > 0 then
    return nil, "Unknown transfer scope: " .. table.concat(unknown, ", ")
  end
  if selected.full_profile then
    return { "full_profile" }
  end
  local normalized = {}
  for _, key in ipairs(SCOPE_ORDER) do
    if selected[key] then
      normalized[#normalized + 1] = key
    end
  end
  if #normalized == 0 then
    return nil, "Select at least one transfer scope."
  end
  return normalized
end

function Package.GetScopeRegistry()
  local result = {}
  for _, key in ipairs(SCOPE_ORDER) do
    result[#result + 1] = Package.Copy(SCOPE_DEFS[key])
  end
  return result
end

function Package.CollectDependencies(scopes)
  local included = {}
  local dependencies = {}
  for _, key in ipairs(type(scopes) == "table" and scopes or {}) do
    included[key] = true
  end
  for _, key in ipairs(type(scopes) == "table" and scopes or {}) do
    local definition = SCOPE_DEFS[key]
    for _, dependency in ipairs(type(definition) == "table" and definition.dependencies or {}) do
      if not included[dependency] then
        dependencies[dependency] = true
      end
    end
  end
  local result = {}
  for _, key in ipairs(SCOPE_ORDER) do
    if dependencies[key] then
      result[#result + 1] = key
    end
  end
  return result
end

function Package.EncodeHeader(metadata)
  local keys = {}
  for key in pairs(type(metadata) == "table" and metadata or {}) do
    keys[#keys + 1] = tostring(key)
  end
  table.sort(keys)
  local lines = {}
  for _, key in ipairs(keys) do
    lines[#lines + 1] = key .. "=" .. Package.Escape(metadata[key])
  end
  return table.concat(lines, "\n")
end

function Package.DecodeHeader(text)
  local metadata = {}
  for line in tostring(text or ""):gmatch("[^\n]+") do
    local separator = line:find("=", 1, true)
    if not separator then
      return nil, "Malformed package metadata line."
    end
    local key = line:sub(1, separator - 1)
    if key == "" or not key:match("^[%w_]+$") or metadata[key] ~= nil then
      return nil, "Malformed or duplicate package metadata key."
    end
    local value, decodeError = Package.Unescape(line:sub(separator + 1))
    if value == nil then
      return nil, decodeError
    end
    metadata[key] = value
  end
  return metadata
end

function Package.EncodeEnvelope(metadata, body)
  local header = Package.EncodeHeader(metadata)
  return PACKAGE_PREFIX .. tostring(#header) .. ":" .. header .. tostring(body or "")
end

function Package.DecodeEnvelope(text)
  if type(text) ~= "string" or text:sub(1, #PACKAGE_PREFIX) ~= PACKAGE_PREFIX then
    return nil, "Package string is not recognized."
  end
  local lengthStart = #PACKAGE_PREFIX + 1
  local separator = text:find(":", lengthStart, true)
  if not separator then
    return nil, "Package header length is missing."
  end
  local lengthText = text:sub(lengthStart, separator - 1)
  if not lengthText:match("^%d+$") then
    return nil, "Package header length is invalid."
  end
  local headerLength = tonumber(lengthText) or 0
  if headerLength < 1 or headerLength > MAX_HEADER_SIZE then
    return nil, "Package header exceeds the supported size."
  end
  local headerStart = separator + 1
  local headerEnd = headerStart + headerLength - 1
  if headerEnd > #text then
    return nil, "Package header is incomplete."
  end
  local metadata, headerError = Package.DecodeHeader(text:sub(headerStart, headerEnd))
  if not metadata then
    return nil, headerError
  end
  return {
    metadata = metadata,
    body = text:sub(headerEnd + 1),
  }
end

function Package.PackSegments(segments)
  local parts = {}
  for _, segment in ipairs(type(segments) == "table" and segments or {}) do
    local key = Package.Trim(type(segment) == "table" and segment.scope or "")
    local payload = type(segment) == "table" and tostring(segment.payload or "") or ""
    parts[#parts + 1] = tostring(#key) .. ":" .. key .. tostring(#payload) .. ":" .. payload
  end
  return table.concat(parts)
end

function Package.ReadLength(text, position)
  local separator = text:find(":", position, true)
  if not separator then
    return nil, nil, "Package segment length is missing."
  end
  local lengthText = text:sub(position, separator - 1)
  if not lengthText:match("^%d+$") then
    return nil, nil, "Package segment length is invalid."
  end
  return tonumber(lengthText) or 0, separator + 1
end

function Package.UnpackSegments(text)
  local segments = {}
  local position = 1
  local seen = {}
  while position <= #text do
    local keyLength, keyStart, keyError = Package.ReadLength(text, position)
    if not keyLength then
      return nil, keyError
    end
    local keyEnd = keyStart + keyLength - 1
    if keyLength < 1 or keyEnd > #text then
      return nil, "Package segment scope is incomplete."
    end
    local key = text:sub(keyStart, keyEnd)
    local payloadLength, payloadStart, payloadError = Package.ReadLength(text, keyEnd + 1)
    if not payloadLength then
      return nil, payloadError
    end
    local payloadEnd = payloadStart + payloadLength - 1
    if payloadEnd > #text then
      return nil, "Package segment payload is incomplete."
    end
    if seen[key] then
      return nil, "Package contains a duplicate scope: " .. key
    end
    seen[key] = true
    segments[#segments + 1] = {
      scope = key,
      payload = text:sub(payloadStart, payloadEnd),
    }
    position = payloadEnd + 1
  end
  return segments
end

function Package.GetAddonVersion()
  if type(C_AddOns) == "table" and type(C_AddOns.GetAddOnMetadata) == "function" then
    local ok, version = pcall(C_AddOns.GetAddOnMetadata, "LidCouncil", "Version")
    if ok and Package.Trim(version) ~= "" then
      return Package.Trim(version)
    end
  end
  if type(GetAddOnMetadata) == "function" then
    local ok, version = pcall(GetAddOnMetadata, "LidCouncil", "Version")
    if ok and Package.Trim(version) ~= "" then
      return Package.Trim(version)
    end
  end
  return "unknown"
end

function Package.Create(deps)
  deps = type(deps) == "table" and deps or {}
  local helpers = {}

  function helpers.GetScopeRegistry()
    return Package.GetScopeRegistry()
  end

  function helpers.BuildScopePayload(profileName, scope)
    local definition = SCOPE_DEFS[scope]
    if type(definition) ~= "table" then
      return nil, "Unknown transfer scope: " .. tostring(scope)
    end
    local exporter
    local payload
    if definition.payloadKind == "full" then
      exporter = deps.ExportLootProfileSnapshot
      if type(exporter) == "function" then
        payload = exporter(profileName)
      end
    elseif definition.payloadKind == "domain" then
      exporter = deps.ExportLootProfileDomainSnapshot
      if type(exporter) == "function" then
        payload = exporter(profileName, definition.domains)
      end
    elseif definition.payloadKind == "subdomain" then
      exporter = deps.ExportLootProfileSubdomainSnapshot
      if type(exporter) == "function" then
        payload = exporter(profileName, definition.subdomains, {
          authoritativeArchiveScope = definition.authoritativeArchiveScope,
        })
      end
    end
    if type(payload) ~= "string" or payload == "" then
      return nil, "Could not export " .. tostring(definition.label or scope) .. "."
    end
    return payload
  end

  function helpers.ExportPackage(profileName, requestedScopes, options)
    local scopes, scopeError = Package.NormalizeScopes(requestedScopes)
    if not scopes then
      return false, scopeError
    end
    local requestedName = Package.Trim(profileName)
    local root = type(deps.RootDB) == "function" and deps.RootDB() or {}
    local storedProfile = type(root) == "table" and type(root.profiles) == "table"
      and root.profiles[requestedName] or nil
    if type(storedProfile) ~= "table" then
      return false, "Profile not found."
    end
    local getProfile = deps.GetLootProfile
    local profile = storedProfile
    local resolvedName = requestedName
    if type(getProfile) == "function" then
      profile, resolvedName = getProfile(requestedName)
    end
    if type(profile) ~= "table" then
      return false, "Profile not found."
    end
    resolvedName = Package.Trim(resolvedName ~= nil and resolvedName or profileName)
    local profileId = Package.Trim(type(profile.meta) == "table" and profile.meta.profileId or "")
    if type(deps.GetLootProfileIdentityInfo) == "function" then
      local identity = deps.GetLootProfileIdentityInfo(resolvedName)
      profileId = Package.Trim(type(identity) == "table" and identity.profileId or profileId)
    end
    if profileId == "" then
      return false, "Profile identity is unavailable."
    end

    local segments = {}
    for _, scope in ipairs(scopes) do
      local payload, payloadError = helpers.BuildScopePayload(resolvedName, scope)
      if not payload then
        return false, payloadError
      end
      segments[#segments + 1] = { scope = scope, payload = payload }
    end
    local body = Package.PackSegments(segments)
    local bodyChecksum = Package.Checksum(deps, body)
    local optionsTable = type(options) == "table" and options or {}
    local partSize = math.max(MIN_PART_SIZE, math.min(MAX_PART_SIZE, tonumber(optionsTable.maxPartChars) or DEFAULT_PART_SIZE))
    local partCount = math.max(1, math.ceil(#body / partSize))
    local exportedAt = math.max(0, tonumber(type(deps.GetTime) == "function" and deps.GetTime() or (time and time() or 0)) or 0)
    local packageId = Package.Checksum(deps,
      profileId .. "|" .. bodyChecksum .. "|" .. tostring(exportedAt) .. "|" .. Package.JoinCsv(scopes))
    local dependencies = Package.CollectDependencies(scopes)
    local packages = {}
    local encodedLength = 0
    for partIndex = 1, partCount do
      local startIndex = (partIndex - 1) * partSize + 1
      local bodyPart = body:sub(startIndex, math.min(#body, startIndex + partSize - 1))
      local metadata = {
        addonVersion = type(deps.GetAddonVersion) == "function" and deps.GetAddonVersion() or Package.GetAddonVersion(),
        bodyLength = #bodyPart,
        dependencies = Package.JoinCsv(dependencies),
        exportedAt = exportedAt,
        formatVersion = PACKAGE_VERSION,
        kind = PACKAGE_KIND,
        packageId = packageId,
        partChecksum = Package.Checksum(deps, bodyPart),
        partCount = partCount,
        partIndex = partIndex,
        payloadChecksum = bodyChecksum,
        payloadLength = #body,
        profileId = profileId,
        profileName = resolvedName,
        schemaVersion = math.max(0, tonumber(type(root) == "table" and root.__schemaVersion or 0) or 0),
        scopes = Package.JoinCsv(scopes),
      }
      local encodedPart = Package.EncodeEnvelope(metadata, bodyPart)
      packages[#packages + 1] = encodedPart
      encodedLength = encodedLength + #encodedPart
    end
    return true, packages, {
      packageId = packageId,
      profileName = resolvedName,
      profileId = profileId,
      scopes = Package.Copy(scopes),
      dependencies = Package.Copy(dependencies),
      partCount = partCount,
      payloadLength = #body,
      encodedLength = encodedLength,
      payloadChecksum = bodyChecksum,
      exportedAt = exportedAt,
    }
  end

  function helpers.DecodePart(text)
    local envelope, envelopeError = Package.DecodeEnvelope(text)
    if not envelope then
      return nil, envelopeError
    end
    local metadata = envelope.metadata
    if metadata.kind ~= PACKAGE_KIND or tonumber(metadata.formatVersion) ~= PACKAGE_VERSION then
      return nil, "Package kind or format version is unsupported."
    end
    local partIndex = math.floor(tonumber(metadata.partIndex) or 0)
    local partCount = math.floor(tonumber(metadata.partCount) or 0)
    local bodyLength = math.floor(tonumber(metadata.bodyLength) or -1)
    if Package.Trim(metadata.packageId) == "" or Package.Trim(metadata.profileId) == ""
      or partIndex < 1 or partCount < 1 or partIndex > partCount
      or bodyLength ~= #envelope.body
    then
      return nil, "Package part metadata is invalid."
    end
    if Package.Trim(metadata.partChecksum) ~= Package.Checksum(deps, envelope.body) then
      return nil, "Package part checksum does not match."
    end
    return {
      metadata = metadata,
      body = envelope.body,
      partIndex = partIndex,
      partCount = partCount,
    }
  end

  function helpers.InspectPackagePart(text)
    local rawText = Package.Trim(text)
    local decoded, decodeError = helpers.DecodePart(rawText)
    if not decoded then
      return {
        valid = false,
        errors = { decodeError },
      }
    end
    local metadata = decoded.metadata
    return {
      valid = true,
      errors = {},
      packageId = metadata.packageId,
      profileName = metadata.profileName,
      profileId = metadata.profileId,
      addonVersion = metadata.addonVersion,
      schemaVersion = tonumber(metadata.schemaVersion) or 0,
      exportedAt = tonumber(metadata.exportedAt) or 0,
      payloadLength = tonumber(metadata.payloadLength) or 0,
      payloadChecksum = metadata.payloadChecksum,
      scopes = Package.SplitCsv(metadata.scopes),
      dependencies = Package.SplitCsv(metadata.dependencies),
      partIndex = decoded.partIndex,
      partCount = decoded.partCount,
      encodedLength = #rawText,
    }
  end

  function helpers.CollectPackagePart(existingCollection, text)
    local rawText = Package.Trim(text)
    local decoded, decodeError = helpers.DecodePart(rawText)
    if not decoded then
      return false, decodeError
    end
    local metadata = decoded.metadata
    local collection = type(existingCollection) == "table" and existingCollection or nil
    if collection then
      local reference = type(collection.metadata) == "table" and collection.metadata or {}
      if metadata.packageId ~= reference.packageId
        or metadata.addonVersion ~= reference.addonVersion
        or metadata.dependencies ~= reference.dependencies
        or metadata.exportedAt ~= reference.exportedAt
        or metadata.formatVersion ~= reference.formatVersion
        or metadata.kind ~= reference.kind
        or metadata.profileId ~= reference.profileId
        or metadata.profileName ~= reference.profileName
        or metadata.payloadChecksum ~= reference.payloadChecksum
        or metadata.payloadLength ~= reference.payloadLength
        or metadata.partCount ~= reference.partCount
        or metadata.schemaVersion ~= reference.schemaVersion
        or metadata.scopes ~= reference.scopes
      then
        return false, "This part belongs to a different package. Clear the received parts before starting another package."
      end
    else
      collection = {
        metadata = Package.Copy(metadata),
        packageId = metadata.packageId,
        profileName = metadata.profileName,
        profileId = metadata.profileId,
        addonVersion = metadata.addonVersion,
        schemaVersion = tonumber(metadata.schemaVersion) or 0,
        exportedAt = tonumber(metadata.exportedAt) or 0,
        payloadLength = tonumber(metadata.payloadLength) or 0,
        payloadChecksum = metadata.payloadChecksum,
        scopes = Package.SplitCsv(metadata.scopes),
        dependencies = Package.SplitCsv(metadata.dependencies),
        partCount = decoded.partCount,
        parts = {},
        receivedCount = 0,
        encodedLength = 0,
      }
    end
    collection.parts = type(collection.parts) == "table" and collection.parts or {}
    local currentPart = collection.parts[decoded.partIndex]
    if currentPart then
      if currentPart ~= rawText then
        return false, "Package part " .. tostring(decoded.partIndex) .. " conflicts with the part already received."
      end
      return true, collection, {
        duplicate = true,
        complete = collection.receivedCount == collection.partCount,
        partIndex = decoded.partIndex,
        partCount = decoded.partCount,
      }
    end
    collection.parts[decoded.partIndex] = rawText
    collection.receivedCount = math.max(0, tonumber(collection.receivedCount) or 0) + 1
    collection.encodedLength = math.max(0, tonumber(collection.encodedLength) or 0) + #rawText
    collection.complete = collection.receivedCount == collection.partCount
    return true, collection, {
      duplicate = false,
      complete = collection.complete,
      partIndex = decoded.partIndex,
      partCount = decoded.partCount,
    }
  end

  function helpers.AssemblePackage(parts)
    local source = type(parts) == "table" and parts or { parts }
    if #source == 0 then
      return nil, "No package parts were provided."
    end
    local decodedByIndex = {}
    local reference
    for _, text in ipairs(source) do
      local decoded, decodeError = helpers.DecodePart(text)
      if not decoded then
        return nil, decodeError
      end
      local metadata = decoded.metadata
      if not reference then
        reference = metadata
      elseif metadata.packageId ~= reference.packageId
        or metadata.addonVersion ~= reference.addonVersion
        or metadata.dependencies ~= reference.dependencies
        or metadata.exportedAt ~= reference.exportedAt
        or metadata.formatVersion ~= reference.formatVersion
        or metadata.kind ~= reference.kind
        or metadata.profileId ~= reference.profileId
        or metadata.profileName ~= reference.profileName
        or metadata.payloadChecksum ~= reference.payloadChecksum
        or metadata.payloadLength ~= reference.payloadLength
        or metadata.partCount ~= reference.partCount
        or metadata.schemaVersion ~= reference.schemaVersion
        or metadata.scopes ~= reference.scopes
      then
        return nil, "Package parts do not belong to the same package."
      end
      if decodedByIndex[decoded.partIndex] then
        return nil, "Package contains duplicate part " .. tostring(decoded.partIndex) .. "."
      end
      decodedByIndex[decoded.partIndex] = decoded
    end
    local expectedParts = tonumber(reference and reference.partCount) or 0
    if #source ~= expectedParts then
      return nil, "Package is incomplete: " .. tostring(#source) .. "/" .. tostring(expectedParts) .. " parts provided."
    end
    local bodyParts = {}
    for index = 1, expectedParts do
      if not decodedByIndex[index] then
        return nil, "Package is missing part " .. tostring(index) .. "."
      end
      bodyParts[#bodyParts + 1] = decodedByIndex[index].body
    end
    local body = table.concat(bodyParts)
    if tonumber(reference.payloadLength) ~= #body then
      return nil, "Assembled package length does not match."
    end
    if Package.Trim(reference.payloadChecksum) ~= Package.Checksum(deps, body) then
      return nil, "Assembled package checksum does not match."
    end
    local segments, segmentError = Package.UnpackSegments(body)
    if not segments then
      return nil, segmentError
    end
    local scopes, scopeError = Package.NormalizeScopes(reference.scopes)
    if not scopes then
      return nil, scopeError
    end
    if #segments ~= #scopes then
      return nil, "Package scope manifest does not match its payload."
    end
    for index, scope in ipairs(scopes) do
      if type(segments[index]) ~= "table" or segments[index].scope ~= scope then
        return nil, "Package scope order does not match its manifest."
      end
    end
    return {
      metadata = Package.Copy(reference),
      scopes = scopes,
      segments = segments,
      dependencies = Package.SplitCsv(reference.dependencies),
      body = body,
    }
  end

  function helpers.PreviewSegment(segment)
    local definition = SCOPE_DEFS[type(segment) == "table" and segment.scope or ""]
    if type(definition) ~= "table" then
      return nil, "Package contains an unsupported scope."
    end
    local previewer = definition.payloadKind == "full" and deps.PreviewLootProfileSnapshot
      or (definition.payloadKind == "domain" and deps.PreviewLootProfileDomainSnapshot
        or deps.PreviewLootProfileSubdomainSnapshot)
    if type(previewer) ~= "function" then
      return nil, "Package preview API is unavailable for " .. definition.label .. "."
    end
    local ok, preview = pcall(previewer, segment.payload)
    if not ok or type(preview) ~= "table" then
      return nil, "Package payload is invalid for " .. definition.label .. "."
    end
    return preview
  end

  function helpers.IsCombatLocked()
    if type(deps.IsCombatLocked) == "function" then
      return deps.IsCombatLocked() == true
    end
    return (type(InCombatLockdown) == "function" and InCombatLockdown())
      or (type(UnitAffectingCombat) == "function" and UnitAffectingCombat("player"))
      or false
  end

  function helpers.InspectPackage(parts, targetName, options)
    local assembled, assembleError = helpers.AssemblePackage(parts)
    if not assembled then
      return {
        valid = false,
        canApply = false,
        errors = { assembleError },
        warnings = {},
        blockers = {},
      }
    end
    local report = {
      valid = true,
      canApply = true,
      errors = {},
      warnings = {},
      blockers = {},
      packageId = assembled.metadata.packageId,
      profileName = assembled.metadata.profileName,
      profileId = assembled.metadata.profileId,
      addonVersion = assembled.metadata.addonVersion,
      schemaVersion = tonumber(assembled.metadata.schemaVersion) or 0,
      exportedAt = tonumber(assembled.metadata.exportedAt) or 0,
      payloadLength = tonumber(assembled.metadata.payloadLength) or #assembled.body,
      partCount = tonumber(assembled.metadata.partCount) or 1,
      scopes = Package.Copy(assembled.scopes),
      dependencies = Package.Copy(assembled.dependencies),
      previews = {},
      effects = {},
    }
    local localRoot = type(deps.RootDB) == "function" and deps.RootDB() or {}
    report.localSchemaVersion = math.max(0, tonumber(type(localRoot) == "table" and localRoot.__schemaVersion or 0) or 0)
    if report.localSchemaVersion > 0 and report.schemaVersion > report.localSchemaVersion then
      report.blockers[#report.blockers + 1] = "This package requires a newer LidCouncil profile schema."
    end
    local localAddonVersion = type(deps.GetAddonVersion) == "function" and Package.Trim(deps.GetAddonVersion()) or ""
    if localAddonVersion ~= "" and localAddonVersion ~= "unknown"
      and report.addonVersion ~= "" and report.addonVersion ~= "unknown"
      and localAddonVersion ~= report.addonVersion
    then
      report.warnings[#report.warnings + 1] = "Package addon version differs from the installed LidCouncil version."
    end
    for _, segment in ipairs(assembled.segments) do
      local preview, previewError = helpers.PreviewSegment(segment)
      if not preview then
        report.valid = false
        report.errors[#report.errors + 1] = previewError
      else
        report.previews[segment.scope] = preview
        local definition = SCOPE_DEFS[segment.scope]
        report.effects[#report.effects + 1] = tostring(definition.label) .. " (" .. tostring(definition.replacement) .. ")"
      end
    end
    for _, dependency in ipairs(assembled.dependencies) do
      local definition = SCOPE_DEFS[dependency]
      report.warnings[#report.warnings + 1] = "For complete derived results, also import "
        .. tostring(type(definition) == "table" and definition.label or dependency) .. "."
    end

    local resolvedTarget = Package.Trim(targetName)
    local optionsTable = type(options) == "table" and options or {}
    if resolvedTarget ~= "" then
      report.targetName = resolvedTarget
      local root = type(deps.RootDB) == "function" and deps.RootDB() or {}
      local profile = type(root) == "table" and type(root.profiles) == "table"
        and root.profiles[resolvedTarget] or nil
      if type(profile) == "table" then
        report.targetExists = true
        local targetId = Package.Trim(type(profile.meta) == "table" and profile.meta.profileId or "")
        if type(deps.GetLootProfileIdentityInfo) == "function" then
          local identity = deps.GetLootProfileIdentityInfo(resolvedTarget)
          targetId = Package.Trim(type(identity) == "table" and identity.profileId or targetId)
        end
        report.targetProfileId = targetId
        if targetId ~= "" and string.lower(targetId) ~= string.lower(report.profileId) then
          report.blockers[#report.blockers + 1] = "Target profile has a different shared profile identity."
        end
      elseif optionsTable.allowCreate == false then
        report.blockers[#report.blockers + 1] = "Target profile does not exist."
      else
        report.targetExists = false
        report.willCreateTarget = true
      end
      if type(deps.FindLootProfileNameById) == "function" then
        local existingName = Package.Trim(deps.FindLootProfileNameById(report.profileId))
        if existingName ~= "" and string.lower(existingName) ~= string.lower(resolvedTarget) then
          report.blockers[#report.blockers + 1] = "This shared profile already exists locally as " .. existingName .. "."
        end
      end
    end
    if type(deps.GetActiveLootSession) == "function" and deps.GetActiveLootSession() then
      report.blockers[#report.blockers + 1] = "Stop the prepared or active session before importing profile data."
    end
    if helpers.IsCombatLocked() then
      report.blockers[#report.blockers + 1] = "Leave combat before importing profile data."
    end
    report.canApply = report.valid and #report.blockers == 0
    return report, assembled
  end

  function helpers.StoreRecoveryBackup(root, targetName, profile, manifest)
    if type(root) ~= "table" or type(profile) ~= "table" then
      return nil
    end
    root.localProfileTransferBackups = type(root.localProfileTransferBackups) == "table"
      and root.localProfileTransferBackups or {}
    local profileId = Package.Trim(type(profile.meta) == "table" and profile.meta.profileId or "")
    local bucketKey = profileId ~= "" and ("profileId:" .. profileId) or ("profileName:" .. targetName)
    local bucket = type(root.localProfileTransferBackups[bucketKey]) == "table"
      and root.localProfileTransferBackups[bucketKey] or { backups = {} }
    root.localProfileTransferBackups[bucketKey] = bucket
    bucket.profileName = targetName
    bucket.profileId = profileId
    bucket.backups = type(bucket.backups) == "table" and bucket.backups or {}
    local createdAt = math.max(0, tonumber(type(deps.GetTime) == "function" and deps.GetTime() or (time and time() or 0)) or 0)
    local record = {
      id = "transfer-" .. tostring(createdAt) .. "-" .. tostring(#bucket.backups + 1),
      createdAt = createdAt,
      packageId = type(manifest) == "table" and manifest.packageId or "",
      scopes = Package.Copy(type(manifest) == "table" and manifest.scopes or {}),
      snapshot = type(deps.DeepCopy) == "function" and deps.DeepCopy(profile) or Package.Copy(profile),
    }
    table.insert(bucket.backups, 1, record)
    return record, bucket
  end

  function helpers.ApplySegment(targetName, segment, profileId, options)
    local definition = SCOPE_DEFS[segment.scope]
    local importer = definition.payloadKind == "full" and deps.ImportLootProfileSnapshot
      or (definition.payloadKind == "domain" and deps.ImportLootProfileDomainSnapshot
        or deps.ImportLootProfileSubdomainSnapshot)
    if type(importer) ~= "function" then
      return false, "Package import API is unavailable for " .. definition.label .. "."
    end
    local importOptions = {
      expectedProfileId = profileId,
      sourceCharacter = Package.Trim(type(options) == "table" and options.sourceCharacter or ""),
      allowAuthoritativeArchiveReplace = definition.replacement == "authoritative",
    }
    local ok, accepted, detail = pcall(importer, targetName, segment.payload, importOptions)
    if not ok then
      return false, tostring(accepted)
    end
    if accepted ~= true then
      return false, tostring(detail or "Package import was rejected.")
    end
    return true
  end

  function helpers.ApplyPackage(parts, targetName, options)
    local resolvedTarget = Package.Trim(targetName)
    if resolvedTarget == "" then
      return false, "Target profile name is required."
    end
    local report, assembled = helpers.InspectPackage(parts, resolvedTarget, options)
    if not report.valid or not report.canApply then
      local firstError = report.errors[1] or report.blockers[1] or "Package cannot be applied."
      return false, firstError, report
    end
    local root = type(deps.RootDB) == "function" and deps.RootDB() or nil
    if type(root) ~= "table" or type(root.profiles) ~= "table" then
      return false, "Profile database is unavailable.", report
    end
    local existingProfile = root.profiles[resolvedTarget]
    local existed = type(existingProfile) == "table"
    local before = existed and (type(deps.DeepCopy) == "function" and deps.DeepCopy(existingProfile) or Package.Copy(existingProfile)) or nil
    local wasEnabled = existed and type(existingProfile.settings) == "table" and existingProfile.settings.enabled == true
    local backupRecord, backupBucket
    if existed then
      backupRecord, backupBucket = helpers.StoreRecoveryBackup(root, resolvedTarget, existingProfile, report)
    end

    local applied, applyError = pcall(function()
      if not existed and assembled.scopes[1] ~= "full_profile" then
        if type(deps.CreateLootProfile) ~= "function" then
          error("Profile creation API is unavailable.")
        end
        local created, createError = deps.CreateLootProfile(resolvedTarget)
        if created ~= true then
          error(tostring(createError or "Target profile could not be created."))
        end
      end
      for _, segment in ipairs(assembled.segments) do
        local accepted, segmentError = helpers.ApplySegment(resolvedTarget, segment, report.profileId, options)
        if not accepted then
          error(segmentError or "Package segment import failed.")
        end
      end
      local appliedProfile = root.profiles[resolvedTarget]
      if type(appliedProfile) ~= "table" then
        error("Imported profile was not created.")
      end
      appliedProfile.settings = type(appliedProfile.settings) == "table" and appliedProfile.settings or {}
      appliedProfile.settings.enabled = existed and wasEnabled or false
    end)

    if not applied then
      if existed then
        root.profiles[resolvedTarget] = before
      else
        root.profiles[resolvedTarget] = nil
      end
      if backupRecord and type(backupBucket) == "table" then
        for index, record in ipairs(backupBucket.backups or {}) do
          if record == backupRecord then
            table.remove(backupBucket.backups, index)
            break
          end
        end
      end
      return false, tostring(applyError), report
    end

    report.applied = true
    report.createdTarget = not existed
    report.recoveryBackupId = backupRecord and backupRecord.id or ""
    if type(backupBucket) == "table" then
      while #(backupBucket.backups or {}) > MAX_RECOVERY_BACKUPS do
        table.remove(backupBucket.backups)
      end
    end
    return true, report
  end

  function helpers.GetRecoveryBackups(profileName)
    local root = type(deps.RootDB) == "function" and deps.RootDB() or {}
    local profile = type(root.profiles) == "table" and root.profiles[profileName] or nil
    local profileId = Package.Trim(type(profile) == "table" and type(profile.meta) == "table" and profile.meta.profileId or "")
    local bucketKey = profileId ~= "" and ("profileId:" .. profileId) or ("profileName:" .. Package.Trim(profileName))
    local bucket
    if type(root.localProfileTransferBackups) == "table" then
      bucket = root.localProfileTransferBackups["profileName:" .. Package.Trim(profileName)]
        or root.localProfileTransferBackups[bucketKey]
    end
    local result = {}
    for _, backup in ipairs(type(bucket) == "table" and bucket.backups or {}) do
      result[#result + 1] = {
        id = backup.id,
        createdAt = backup.createdAt,
        packageId = backup.packageId,
        scopes = Package.Copy(backup.scopes),
      }
    end
    return result
  end

  function helpers.RestoreRecoveryBackup(profileName, backupId)
    if type(deps.GetActiveLootSession) == "function" and deps.GetActiveLootSession() then
      return false, "Stop the prepared or active session before restoring transferred data."
    end
    if helpers.IsCombatLocked() then
      return false, "Leave combat before restoring transferred data."
    end
    local root = type(deps.RootDB) == "function" and deps.RootDB() or {}
    local profile = type(root.profiles) == "table" and root.profiles[profileName] or nil
    local profileId = Package.Trim(type(profile) == "table" and type(profile.meta) == "table" and profile.meta.profileId or "")
    local bucketKey = profileId ~= "" and ("profileId:" .. profileId) or ("profileName:" .. Package.Trim(profileName))
    local bucket
    if type(root.localProfileTransferBackups) == "table" then
      bucket = root.localProfileTransferBackups["profileName:" .. Package.Trim(profileName)]
        or root.localProfileTransferBackups[bucketKey]
    end
    for _, backup in ipairs(type(bucket) == "table" and bucket.backups or {}) do
      if tostring(backup.id) == tostring(backupId) and type(backup.snapshot) == "table" then
        root.profiles[profileName] = type(deps.DeepCopy) == "function" and deps.DeepCopy(backup.snapshot) or Package.Copy(backup.snapshot)
        return true, backup.id
      end
    end
    return false, "Transfer recovery backup was not found."
  end

  return helpers
end

function Package.RunValidation()
  local checks = {}
  local problems = {}
  local function check(name, passed)
    checks[#checks + 1] = { name = name, passed = passed == true }
    if passed ~= true then problems[#problems + 1] = name end
  end

  local root = {
    __schemaVersion = 4,
    profiles = {
      Host = { meta = { profileId = "shared-1" }, settings = { enabled = false }, marker = "host" },
      Target = { meta = { profileId = "shared-1" }, settings = { enabled = false }, marker = "before" },
      LegacyTarget = { meta = {}, settings = { enabled = false }, marker = "legacy-before" },
      Other = { meta = { profileId = "shared-2" }, settings = { enabled = false }, marker = "other" },
    },
  }
  local activeSession = false
  local combatLocked = false
  local failPermissions = false
  local authoritativeSeen = false
  local now = 100
  local function getProfile(name) return root.profiles[name], name end
  local function identity(name)
    local profile = root.profiles[name]
    return type(profile) == "table" and { profileId = profile.meta.profileId } or nil
  end
  local function preview(payload)
    return type(payload) == "string" and payload ~= "" and { profileId = "shared-1" } or nil
  end
  local deps = {
    RootDB = function() return root end,
    DeepCopy = Package.Copy,
    CalculateStableChecksum = function(value) return Package.Checksum(nil, value) end,
    GetLootProfile = getProfile,
    GetLootProfileIdentityInfo = identity,
    FindLootProfileNameById = function() return "" end,
    GetActiveLootSession = function() return activeSession and {} or nil end,
    IsCombatLocked = function() return combatLocked end,
    GetTime = function() now = now + 1 return now end,
    GetAddonVersion = function() return "validation" end,
    CreateLootProfile = function(name)
      if root.profiles[name] then return false, "exists" end
      root.profiles[name] = { meta = { profileId = "temporary" }, settings = { enabled = false } }
      return true, name
    end,
    ExportLootProfileSnapshot = function() return "FULL:shared-1" end,
    ExportLootProfileDomainSnapshot = function(_, domains) return "DOMAIN:" .. tostring(domains[1]) end,
    ExportLootProfileSubdomainSnapshot = function(_, subdomains, options)
      return "SUB:" .. tostring(options and options.authoritativeArchiveScope or (subdomains and subdomains[1]) or "empty")
    end,
    PreviewLootProfileSnapshot = preview,
    PreviewLootProfileDomainSnapshot = preview,
    PreviewLootProfileSubdomainSnapshot = preview,
    ImportLootProfileSnapshot = function(name)
      root.profiles[name] = { meta = { profileId = "shared-1" }, settings = { enabled = true }, marker = "full" }
      return true, name, "shared-1"
    end,
    ImportLootProfileDomainSnapshot = function(name, payload)
      if failPermissions and payload == "DOMAIN:permissions" then return false, "forced failure" end
      root.profiles[name].marker = payload
      root.profiles[name].meta.profileId = "shared-1"
      return true, name, "shared-1"
    end,
    ImportLootProfileSubdomainSnapshot = function(name, payload, options)
      authoritativeSeen = options and options.allowAuthoritativeArchiveReplace == true
      root.profiles[name].marker = payload
      root.profiles[name].meta.profileId = "shared-1"
      return true, name, "shared-1"
    end,
  }
  local helpers = Package.Create(deps)

  local scopes = helpers.GetScopeRegistry()
  check("scope registry exposes seven canonical packages", #scopes == 7)
  check("Fun Awards declares Loot List dependency",
    type(scopes[7].dependencies) == "table" and scopes[7].dependencies[1] == "loot_list")
  local normalized = Package.NormalizeScopes({ "loot", "sessions" })
  check("scope aliases normalize deterministically", normalized and normalized[1] == "loot_list" and normalized[2] == "session_history")
  local full = Package.NormalizeScopes({ "loot_list", "full_profile" })
  check("full profile supersedes narrower scopes", full and #full == 1 and full[1] == "full_profile")
  local unknown = Package.NormalizeScopes({ "not-a-scope" })
  check("unknown scope is rejected", unknown == nil)
  local escapedHeader = Package.EncodeHeader({ note = "100% ready = yes" })
  local decodedHeader = Package.DecodeHeader(escapedHeader)
  check("metadata escaping preserves percent and separators", decodedHeader and decodedHeader.note == "100% ready = yes")
  check("malformed metadata escape is rejected", Package.DecodeHeader("note=%GG") == nil)

  local exported, parts, manifest = helpers.ExportPackage("Host", { "loot_list", "session_history" }, { maxPartChars = 4000 })
  check("scoped package exports", exported and type(parts) == "table" and #parts == 1)
  check("export manifest preserves shared identity", manifest and manifest.profileId == "shared-1")
  local inspection = helpers.InspectPackage(parts, "Target")
  check("multi-scope bundle preserves ordered scopes and dry-run effects",
    manifest and type(manifest.scopes) == "table"
      and manifest.scopes[1] == "loot_list" and manifest.scopes[2] == "session_history"
      and inspection and type(inspection.effects) == "table" and #inspection.effects == 2)
  check("dry-run inspection accepts matching target", inspection.valid and inspection.canApply)
  check("dry-run inspection does not mutate target", root.profiles.Target.marker == "before")
  local missingInspection = helpers.InspectPackage(parts, "MissingTarget")
  check("dry-run inspection does not create a missing target", missingInspection.willCreateTarget == true
    and root.profiles.MissingTarget == nil)
  local missingExport = helpers.ExportPackage("MissingSource", { "full_profile" })
  check("export rejects missing source without creating it", missingExport == false and root.profiles.MissingSource == nil)
  root.__schemaVersion = 3
  local newerSchemaInspection = helpers.InspectPackage(parts, "Target")
  check("newer profile schema blocks import", newerSchemaInspection.valid and not newerSchemaInspection.canApply)
  root.__schemaVersion = 4

  local multipartOk, multipart = helpers.ExportPackage("Host", { "full_profile" }, { maxPartChars = 4 })
  check("minimum multipart size is bounded", multipartOk and #multipart == 1)
  local longPayload = string.rep("x", 9000)
  deps.ExportLootProfileSnapshot = function() return longPayload end
  local longHelpers = Package.Create(deps)
  local longOk, longParts = longHelpers.ExportPackage("Host", { "full_profile" }, { maxPartChars = 4000 })
  check("large package splits into ordered parts", longOk and #longParts >= 3)
  local partInspection = longHelpers.InspectPackagePart(longParts[2])
  check("individual package part inspection validates metadata and checksum",
    partInspection.valid and partInspection.partIndex == 2 and partInspection.partCount == #longParts)
  local collected
  local collectSecond, nextCollection = longHelpers.CollectPackagePart(collected, longParts[2])
  collected = nextCollection
  local duplicateSecond, duplicateCollection, duplicateDetail = longHelpers.CollectPackagePart(collected, longParts[2])
  collected = duplicateCollection
  check("multipart collector accepts out-of-order and duplicate-identical parts",
    collectSecond and duplicateSecond and duplicateDetail.duplicate == true and collected.receivedCount == 1)
  local mixedAccepted = longHelpers.CollectPackagePart(collected, parts[1])
  check("multipart collector rejects mixed packages", mixedAccepted == false)
  for index, packagePart in ipairs(longParts) do
    if index ~= 2 then
      local accepted, updated = longHelpers.CollectPackagePart(collected, packagePart)
      if accepted then collected = updated end
    end
  end
  local collectedParts = {}
  for index = 1, collected.partCount do collectedParts[index] = collected.parts[index] end
  local collectedInspection = longHelpers.InspectPackage(collectedParts, "Target")
  check("completed multipart collection passes full package inspection",
    collected.complete == true and collectedInspection.valid == true)
  local reversed = {}
  for index = #longParts, 1, -1 do reversed[#reversed + 1] = longParts[index] end
  local assembled = longHelpers.AssemblePackage(reversed)
  check("multipart assembly accepts out-of-order input", type(assembled) == "table" and assembled.body:find(longPayload, 1, true) ~= nil)
  local incomplete = { longParts[1] }
  check("incomplete multipart package is rejected", longHelpers.AssemblePackage(incomplete) == nil)
  local tampered = { longParts[1]:sub(1, -2) .. (longParts[1]:sub(-1) == "x" and "y" or "x") }
  check("tampered package part is rejected", longHelpers.AssemblePackage(tampered) == nil)

  deps.ExportLootProfileSnapshot = function() return "FULL:shared-1" end
  local fullHelpers = Package.Create(deps)
  local fullOk, fullParts = fullHelpers.ExportPackage("Host", { "full_profile" })
  local fullApplied = fullHelpers.ApplyPackage(fullParts, "Target")
  check("full package replaces a matching shared profile", fullOk and fullApplied == true
    and root.profiles.Target.marker == "full" and root.profiles.Target.settings.enabled == false)
  root.profiles.Target = { meta = { profileId = "shared-1" }, settings = { enabled = false }, marker = "before" }
  root.localProfileTransferBackups = nil

  local mismatch = helpers.InspectPackage(parts, "Other")
  check("profile identity mismatch blocks import", mismatch.valid and not mismatch.canApply)
  activeSession = true
  local sessionBlocked = helpers.InspectPackage(parts, "Target")
  check("prepared or active session blocks import", not sessionBlocked.canApply)
  activeSession = false
  combatLocked = true
  local combatBlocked = helpers.InspectPackage(parts, "Target")
  check("combat blocks import", not combatBlocked.canApply)
  combatLocked = false

  local awardsOk, awardsParts = helpers.ExportPackage("Host", { "fun_awards" })
  local awardsInspection = helpers.InspectPackage(awardsParts, "Target")
  check("Fun Awards dependency is reported", awardsOk and #awardsInspection.warnings == 1)
  local applied = helpers.ApplyPackage(awardsParts, "Target")
  check("authoritative empty-capable scope applies", applied == true and authoritativeSeen)
  check("successful replacement stores recovery backup", #helpers.GetRecoveryBackups("Target") == 1)

  local recoveryBucket = root.localProfileTransferBackups and root.localProfileTransferBackups["profileId:shared-1"]
  recoveryBucket = type(recoveryBucket) == "table" and recoveryBucket or { backups = {} }
  recoveryBucket.backups = type(recoveryBucket.backups) == "table" and recoveryBucket.backups or {}
  recoveryBucket.backups[#recoveryBucket.backups + 1] = {
    id = "older-2", createdAt = 2, snapshot = Package.Copy(root.profiles.Target), scopes = {},
  }
  recoveryBucket.backups[#recoveryBucket.backups + 1] = {
    id = "older-3", createdAt = 1, snapshot = Package.Copy(root.profiles.Target), scopes = {},
  }
  root.profiles.Target.marker = "rollback-source"
  local transactionOk, transactionParts = helpers.ExportPackage("Host", { "profile_setup", "roles_rights" })
  failPermissions = true
  local transactionApplied = helpers.ApplyPackage(transactionParts, "Target")
  failPermissions = false
  check("failed multi-scope import rolls back", transactionOk and transactionApplied == false and root.profiles.Target.marker == "rollback-source")
  local retainedBackups = helpers.GetRecoveryBackups("Target")
  check("failed transaction preserves full recovery history", #retainedBackups == 3
    and retainedBackups[3] and retainedBackups[3].id == "older-3")

  local createOk, createParts = helpers.ExportPackage("Host", { "profile_setup" })
  local created = helpers.ApplyPackage(createParts, "NewReplica")
  check("scoped package can seed an inactive shared replica", createOk and created == true
    and root.profiles.NewReplica.meta.profileId == "shared-1" and root.profiles.NewReplica.settings.enabled == false)
  local legacyApplied = helpers.ApplyPackage(createParts, "LegacyTarget")
  check("legacy target recovery remains discoverable after identity adoption", legacyApplied == true
    and #helpers.GetRecoveryBackups("LegacyTarget") == 1)

  local restoreList = helpers.GetRecoveryBackups("Target")
  root.profiles.Target.marker = "changed-after-import"
  local restored = helpers.RestoreRecoveryBackup("Target", restoreList[1] and restoreList[1].id)
  check("transfer recovery backup restores previous profile", restored == true and root.profiles.Target.marker == "before")

  local passed = 0
  for _, entry in ipairs(checks) do if entry.passed then passed = passed + 1 end end
  return passed == #checks, {
    version = 1,
    total = #checks,
    passed = passed,
    failed = #checks - passed,
    checks = checks,
    problems = problems,
  }
end

INTERNAL_API.LIDCOUNCIL_CreateProfileTransferPackageHelpers_Impl = Package.Create

local profileTransferPackages = Package.Create({
  RootDB = API.LIDCOUNCIL_RootDB,
  DeepCopy = API.LIDCOUNCIL_DeepCopy,
  CalculateStableChecksum = API.LIDCOUNCIL_CalculateStableChecksum,
  GetLootProfile = API.LIDCOUNCIL_GetLootProfile,
  GetLootProfileIdentityInfo = API.LIDCOUNCIL_GetLootProfileIdentityInfo,
  FindLootProfileNameById = API.LIDCOUNCIL_FindLootProfileNameById,
  GetActiveLootSession = API.LIDCOUNCIL_GetActiveLootSession,
  CreateLootProfile = API.LIDCOUNCIL_CreateLootProfile,
  ExportLootProfileSnapshot = API.LIDCOUNCIL_ExportLootProfileSnapshot,
  ExportLootProfileDomainSnapshot = API.LIDCOUNCIL_ExportLootProfileDomainSnapshot,
  ExportLootProfileSubdomainSnapshot = API.LIDCOUNCIL_ExportLootProfileSubdomainSnapshot,
  PreviewLootProfileSnapshot = API.LIDCOUNCIL_PreviewLootProfileSnapshot,
  PreviewLootProfileDomainSnapshot = API.LIDCOUNCIL_PreviewLootProfileDomainSnapshot,
  PreviewLootProfileSubdomainSnapshot = API.LIDCOUNCIL_PreviewLootProfileSubdomainSnapshot,
  ImportLootProfileSnapshot = API.LIDCOUNCIL_ImportLootProfileSnapshot,
  ImportLootProfileDomainSnapshot = API.LIDCOUNCIL_ImportLootProfileDomainSnapshot,
  ImportLootProfileSubdomainSnapshot = API.LIDCOUNCIL_ImportLootProfileSubdomainSnapshot,
  GetAddonVersion = Package.GetAddonVersion,
})

API.LIDCOUNCIL_GetProfileTransferScopeRegistry = profileTransferPackages.GetScopeRegistry
API.LIDCOUNCIL_ExportSharedProfilePackage = profileTransferPackages.ExportPackage
API.LIDCOUNCIL_InspectSharedProfilePackagePart = profileTransferPackages.InspectPackagePart
API.LIDCOUNCIL_CollectSharedProfilePackagePart = profileTransferPackages.CollectPackagePart
API.LIDCOUNCIL_InspectSharedProfilePackage = profileTransferPackages.InspectPackage
API.LIDCOUNCIL_ApplySharedProfilePackage = profileTransferPackages.ApplyPackage
API.LIDCOUNCIL_GetProfileTransferRecoveryBackups = profileTransferPackages.GetRecoveryBackups
API.LIDCOUNCIL_RestoreProfileTransferRecoveryBackup = profileTransferPackages.RestoreRecoveryBackup
API.LIDCOUNCIL_RunProfileTransferPackageValidation = Package.RunValidation
