local Compat = _G.LIDCOUNCIL_Compat

_G.LIDCOUNCIL_CreateCoreProfileSyncSupportHelpers_Impl = function(deps)
  deps = type(deps) == "table" and deps or {}

  local TrimText = deps.TrimText
  local EnsureLootLedgerMeta = deps.EnsureLootLedgerMeta
  local NormalizeLootLedgerMainAltRole = deps.NormalizeLootLedgerMainAltRole
  local TouchLootProfileSettings = deps.TouchLootProfileSettings
  local TouchLootProfilePermissions = deps.TouchLootProfilePermissions
  local TouchLootProfileOperational = deps.TouchLootProfileOperational
  local GetLootProfile = deps.GetLootProfile
  local GetLootProfileRole = deps.GetLootProfileRole
  local GetLootProfileAccessInfoForRole = deps.GetLootProfileAccessInfoForRole
  local EnsureLootProfilePermissionState = deps.EnsureLootProfilePermissionState
  local NormalizeLootRollTemplate = deps.NormalizeLootRollTemplate
  local GetLootRollTemplateOptions = deps.GetLootRollTemplateOptions
  local NormalizeLootRollOptions = deps.NormalizeLootRollOptions
  local CUSTOM_LOOT_ROLL_TEMPLATE = deps.CUSTOM_LOOT_ROLL_TEMPLATE or "CUSTOM"
  local NormalizePointMode = deps.NormalizePointMode
  local EnsureLidTableRows = deps.EnsureLidTableRows
  local ExtractItemID = deps.ExtractItemID
  local SetLootProfilePermissionMember = deps.SetLootProfilePermissionMember
  local NormalizeLootProfileRole = deps.NormalizeLootProfileRole
  local SetLootProfileMemberRole = deps.SetLootProfileMemberRole
  local SetLootProfilePermissionPolicyValue = deps.SetLootProfilePermissionPolicyValue
  local AddLootLedgerEntry = deps.AddLootLedgerEntry
  local RemoveLootLedgerEntry = deps.RemoveLootLedgerEntry

  local function trim(value)
    if type(TrimText) == "function" then
      return TrimText(value)
    end
    local text = tostring(value or "")
    text = text:gsub("^%s+", "")
    text = text:gsub("%s+$", "")
    return text
  end

  local function ResolveOptionalApiFunction(name)
    local api = rawget(_G, "LIDCOUNCIL_API")
    local resolvedName = trim(name)
    if type(api) == "table" and type(api[resolvedName]) == "function" then
      return api[resolvedName]
    end
    local globalFn = rawget(_G, resolvedName)
    if type(globalFn) == "function" then
      return globalFn
    end
    return nil
  end

  local PROFILE_CHANGE_SYNC_MIN_INTERVAL_SECONDS = 6
  local pendingProfileChangeSyncs = {}
  local pendingProfileChangeTimers = {}
  local lastProfileChangeSyncAt = {}
  local profileChangeSyncSuppressionDepth = 0

  local function GetProfileChangeSyncTime()
    if type(GetTime) == "function" then
      return tonumber(GetTime()) or 0
    end
    return tonumber(time and time() or 0) or 0
  end

  local function SendActiveProfileChangeNow(profileName, reason)
    local broadcastProfileUpdate = ResolveOptionalApiFunction("LIDCOUNCIL_BroadcastActiveProfileSnapshotFlow")
    if type(broadcastProfileUpdate) ~= "function" then
      return false
    end
    return broadcastProfileUpdate(profileName, reason)
  end

  local function FlushPendingProfileChangeSync(profileName)
    local resolvedName = trim(profileName)
    if resolvedName == "" then
      return
    end
    local pending = pendingProfileChangeSyncs[resolvedName]
    pendingProfileChangeSyncs[resolvedName] = nil
    pendingProfileChangeTimers[resolvedName] = nil
    if type(pending) ~= "table" then
      return
    end
    lastProfileChangeSyncAt[resolvedName] = GetProfileChangeSyncTime()
    SendActiveProfileChangeNow(resolvedName, pending.reason)
  end

  local function QueueSettingsProfileChangeSync(profileName, reason)
    local resolvedName = trim(profileName)
    if resolvedName == "" then
      return false
    end

    local now = GetProfileChangeSyncTime()
    local lastSent = tonumber(lastProfileChangeSyncAt[resolvedName]) or 0
    if not pendingProfileChangeTimers[resolvedName]
        and (lastSent <= 0 or (now - lastSent) >= PROFILE_CHANGE_SYNC_MIN_INTERVAL_SECONDS) then
      lastProfileChangeSyncAt[resolvedName] = now
      return SendActiveProfileChangeNow(resolvedName, reason)
    end

    pendingProfileChangeSyncs[resolvedName] = {
      reason = trim(reason) ~= "" and trim(reason) or "settings",
    }
    if pendingProfileChangeTimers[resolvedName] then
      return true, "queued"
    end

    if type(Compat) ~= "table" or type(Compat.After) ~= "function" then
      pendingProfileChangeSyncs[resolvedName] = nil
      lastProfileChangeSyncAt[resolvedName] = now
      return SendActiveProfileChangeNow(resolvedName, reason)
    end

    local delay = math.max(1, PROFILE_CHANGE_SYNC_MIN_INTERVAL_SECONDS - math.max(0, now - lastSent))
    pendingProfileChangeTimers[resolvedName] = true
    Compat.After(delay, function()
      FlushPendingProfileChangeSync(resolvedName)
    end)
    return true, "queued"
  end

  local function BroadcastActiveProfileChange(profileName, reason, change)
    if profileChangeSyncSuppressionDepth > 0 then
      return true, "suppressed"
    end
    if type(change) == "table" then
      local broadcastProfileDelta = ResolveOptionalApiFunction("LIDCOUNCIL_BroadcastActiveProfileDeltaFlow")
      if type(broadcastProfileDelta) == "function" then
        local ok, result = broadcastProfileDelta(profileName, reason, change)
        if ok then
          return ok, result
        end
      end
    end
    if trim(reason) == "settings" then
      return QueueSettingsProfileChangeSync(profileName, reason)
    end
    return SendActiveProfileChangeNow(profileName, reason)
  end

  local function WithSuppressedProfileChangeSync(callback)
    profileChangeSyncSuppressionDepth = profileChangeSyncSuppressionDepth + 1
    local ok, a, b, c = pcall(callback)
    profileChangeSyncSuppressionDepth = math.max(0, profileChangeSyncSuppressionDepth - 1)
    if not ok then
      return false, a
    end
    return a, b, c
  end

  local function EncodeRollOptionColor(color)
    color = type(color) == "table" and color or {}
    return table.concat({
      tostring(tonumber(color[1]) or tonumber(color.r) or 0.82),
      tostring(tonumber(color[2]) or tonumber(color.g) or 0.82),
      tostring(tonumber(color[3]) or tonumber(color.b) or 0.86),
    }, ",")
  end

  local function DecodeRollOptionColor(value)
    local text = trim(value)
    local r, g, b = text:match("^([^,]+),([^,]+),([^,]+)$")
    return {
      tonumber(r) or 0.82,
      tonumber(g) or 0.82,
      tonumber(b) or 0.86,
    }
  end

  local function BuildRollOptionDeltaArgs(index, option)
    option = type(option) == "table" and option or {}
    return {
      tostring(tonumber(index) or 0),
      trim(option.label),
      trim(option.key),
      EncodeRollOptionColor(option.color),
      trim(option.icon),
      trim(option.pointBehavior),
      trim(option.popupSection),
    }
  end

  local function BuildLidTableRowDeltaArgs(index, row)
    row = type(row) == "table" and row or {}
    return {
      tostring(tonumber(index) or 0),
      tostring(row.points ~= nil and row.points or ""),
      tostring(row.itemLevel ~= nil and row.itemLevel or ""),
      tostring(row.setPiecePoints ~= nil and row.setPiecePoints or ""),
      tostring(row.offSpecPoints ~= nil and row.offSpecPoints or ""),
      tostring(row.transmogPoints ~= nil and row.transmogPoints or ""),
      tostring(row.disenchantPoints ~= nil and row.disenchantPoints or ""),
    }
  end

  local function FindLootLedgerEntryById(profile, characterKey, entryId)
    local resolvedCharacter = trim(characterKey)
    local resolvedEntryId = trim(entryId)
    if type(profile) ~= "table" or resolvedCharacter == "" or resolvedEntryId == "" then
      return nil
    end
    local ledger = type(profile.lootLedger) == "table" and profile.lootLedger or nil
    local row = type(ledger) == "table" and ledger[resolvedCharacter] or nil
    if type(row) ~= "table" or type(row.items) ~= "table" then
      return nil
    end
    for _, item in ipairs(row.items) do
      if type(item) == "table" and trim(item.entryId) == resolvedEntryId then
        return item, row
      end
    end
    return nil, row
  end

  local function EnsureLootLedgerMetaDeltaEntry(profile, characterKey)
    local resolvedCharacter = trim(characterKey)
    if type(profile) ~= "table" or resolvedCharacter == "" then
      return nil, nil
    end
    local metaByCharacter = type(EnsureLootLedgerMeta) == "function" and EnsureLootLedgerMeta(profile) or nil
    if type(metaByCharacter) ~= "table" then
      profile.lootLedgerMeta = type(profile.lootLedgerMeta) == "table" and profile.lootLedgerMeta or {}
      metaByCharacter = profile.lootLedgerMeta
    end
    local meta = type(metaByCharacter[resolvedCharacter]) == "table" and metaByCharacter[resolvedCharacter] or {
      penaltyPoints = 0,
      classFile = "",
      className = "",
      specName = "",
      specID = nil,
      specIcon = "",
      note = "",
      mainAltRole = "MAIN",
      mainCharacter = "",
    }
    meta.penaltyPoints = tonumber(meta.penaltyPoints) or 0
    meta.classFile = trim(meta.classFile)
    meta.className = trim(meta.className)
    meta.specName = trim(meta.specName)
    meta.specID = tonumber(meta.specID)
    meta.specID = meta.specID and meta.specID > 0 and math.floor(meta.specID) or nil
    meta.specIcon = trim(meta.specIcon)
    meta.note = trim(meta.note)
    meta.mainAltRole = type(NormalizeLootLedgerMainAltRole) == "function" and NormalizeLootLedgerMainAltRole(meta.mainAltRole) or "MAIN"
    meta.mainCharacter = trim(meta.mainCharacter)
    if meta.mainAltRole == "MAIN" or string.lower(meta.mainCharacter) == string.lower(resolvedCharacter) then
      meta.mainCharacter = ""
    end
    meta.summaryWith = nil
    metaByCharacter[resolvedCharacter] = meta
    return meta, metaByCharacter
  end

  local function ApplyLootLedgerManualAddDelta(profileName, profile, args)
    local characterKey = trim(args[1])
    local entryId = trim(args[2])
    local itemName = trim(args[3])
    local points = tonumber(args[4]) or 0
    local note = trim(args[5])
    local grantedBy = trim(args[6])
    local awardedAt = tonumber(args[7]) or 0
    local sessionId = trim(args[8])
    if characterKey == "" or entryId == "" or itemName == "" then
      return false, "Manual ledger delta is incomplete."
    end
    if FindLootLedgerEntryById(profile, characterKey, entryId) then
      return true
    end
    if type(AddLootLedgerEntry) ~= "function" then
      return false, "Loot list ledger API is unavailable."
    end
    return AddLootLedgerEntry(
      profileName,
      characterKey,
      itemName,
      nil,
      points,
      note,
      nil,
      nil,
      "Interface\\Icons\\INV_Misc_Note_06",
      nil,
      {
        entryId = entryId,
        awardedAt = awardedAt > 0 and awardedAt or nil,
        grantedBy = grantedBy,
        sessionId = sessionId,
        isManual = true,
      }
    )
  end

  local function ApplyLootLedgerManualDeleteDelta(profileName, profile, args)
    local characterKey = trim(args[1])
    local entryId = trim(args[2])
    if characterKey == "" or entryId == "" then
      return false, "Manual ledger delete delta is incomplete."
    end
    if not FindLootLedgerEntryById(profile, characterKey, entryId) then
      return true
    end
    if type(RemoveLootLedgerEntry) ~= "function" then
      return false, "Loot list ledger API is unavailable."
    end
    return RemoveLootLedgerEntry(profileName, characterKey, entryId)
  end

  local function ApplyLootLedgerMainAltDelta(profile, args)
    local characterKey = trim(args[1])
    local role = type(NormalizeLootLedgerMainAltRole) == "function" and NormalizeLootLedgerMainAltRole(args[2]) or "MAIN"
    local mainCharacter = trim(args[3])
    if characterKey == "" then
      return false, "Character-Realm is required."
    end
    local meta = EnsureLootLedgerMetaDeltaEntry(profile, characterKey)
    if type(meta) ~= "table" then
      return false, "Loot list metadata is unavailable."
    end
    if role == "ALT" then
      meta.mainAltRole = "ALT"
      meta.mainCharacter = string.lower(mainCharacter) == string.lower(characterKey) and "" or mainCharacter
    else
      meta.mainAltRole = "MAIN"
      meta.mainCharacter = ""
    end
    if type(TouchLootProfileOperational) == "function" then
      TouchLootProfileOperational(profile)
    end
    return true
  end

  local function ApplyLootLedgerNoteDelta(profile, args)
    local characterKey = trim(args[1])
    if characterKey == "" then
      return false, "Character-Realm is required."
    end
    local meta = EnsureLootLedgerMetaDeltaEntry(profile, characterKey)
    if type(meta) ~= "table" then
      return false, "Loot list metadata is unavailable."
    end
    meta.note = trim(args[2])
    if type(TouchLootProfileOperational) == "function" then
      TouchLootProfileOperational(profile)
    end
    return true, meta.note
  end

  local function ApplyLootLedgerCharacterDeleteDelta(profile, args)
    local characterKey = trim(args[1])
    if type(profile) ~= "table" or characterKey == "" then
      return false, "Character-Realm is required."
    end
    local removed = false
    profile.lootLedger = type(profile.lootLedger) == "table" and profile.lootLedger or {}
    local metaByCharacter = type(EnsureLootLedgerMeta) == "function" and EnsureLootLedgerMeta(profile) or {}
    if type(profile.lootLedger[characterKey]) == "table" then
      profile.lootLedger[characterKey] = nil
      removed = true
    end
    if type(metaByCharacter[characterKey]) == "table" then
      metaByCharacter[characterKey] = nil
      removed = true
    end
    for _, group in ipairs(type(profile.lootListGroups) == "table" and profile.lootListGroups or {}) do
      if type(group) == "table" and type(group.members) == "table" then
        for index = #group.members, 1, -1 do
          if trim(group.members[index]) == characterKey then
            table.remove(group.members, index)
            removed = true
          end
        end
      end
    end
    local deletedLower = string.lower(characterKey)
    for _, meta in pairs(type(metaByCharacter) == "table" and metaByCharacter or {}) do
      if type(meta) == "table" and string.lower(trim(meta.mainCharacter)) == deletedLower then
        meta.mainCharacter = ""
        meta.mainAltRole = "MAIN"
        removed = true
      end
    end
    if not removed then
      return true
    end
    if type(TouchLootProfileOperational) == "function" then
      TouchLootProfileOperational(profile)
    end
    return true
  end

  local function ApplyIncomingLootProfileDelta(name, domain, action, args, opts)
    opts = type(opts) == "table" and opts or {}
    args = type(args) == "table" and args or {}
    local profile = type(GetLootProfile) == "function" and GetLootProfile(name) or nil
    if type(profile) ~= "table" then
      return false, "Profile not found."
    end

    local resolvedAction = string.upper(trim(action))
    local actorKey = trim(opts.actor)
    local skipAccessCheck = opts.skipAccessCheck == true
    if not skipAccessCheck then
      local actorRole = type(GetLootProfileRole) == "function" and GetLootProfileRole(name, actorKey) or nil
      local actorAccess = type(GetLootProfileAccessInfoForRole) == "function" and GetLootProfileAccessInfoForRole(name, actorRole) or {}
      local requiredAccess
      if resolvedAction == "SET_RAID" then
        requiredAccess = "canEditRaidSettings"
      elseif resolvedAction == "ROLE_SET" or resolvedAction == "POLICY_SET" then
        requiredAccess = "canManageRights"
      elseif resolvedAction == "LEDGER_MANUAL_ADD" or resolvedAction == "LEDGER_MANUAL_DELETE" then
        requiredAccess = "canEditManualPoints"
      elseif resolvedAction == "LEDGER_MAIN_ALT_SET" then
        requiredAccess = "canEditMainAlt"
      elseif resolvedAction == "LEDGER_NOTE_SET" then
        requiredAccess = "canEditNotes"
      elseif resolvedAction == "LEDGER_CHARACTER_DELETE" then
        requiredAccess = "canDeleteLootListCharacter"
      else
        requiredAccess = "canEditRollSettings"
        if resolvedAction == "POINT_MODE" or resolvedAction == "LID_TABLE_ROW" or resolvedAction == "POINT_RULE_ADD" or resolvedAction == "POINT_RULE_REMOVE" then
          requiredAccess = "canEditPointSettings"
        end
      end
      if not (type(actorAccess) == "table" and actorAccess[requiredAccess]) then
        return false, "Actor is not allowed to apply this profile delta."
      end
    end

    return WithSuppressedProfileChangeSync(function()
      if resolvedAction == "SET_RAID" then
        profile.settings.raid = profile.settings.raid or {}
        local raidName = trim(args[1])
        profile.settings.raid.name = raidName ~= "" and raidName or nil
        profile.settings.raid.instanceID = tonumber(args[2])
        if type(TouchLootProfileSettings) == "function" then
          TouchLootProfileSettings(profile)
        end
        return true
      elseif resolvedAction == "ROLL_TEMPLATE" then
        local resolvedTemplate = type(NormalizeLootRollTemplate) == "function" and NormalizeLootRollTemplate(args[1]) or trim(args[1])
        profile.settings.rollTemplate = resolvedTemplate
        profile.settings.rollOptions = type(GetLootRollTemplateOptions) == "function" and GetLootRollTemplateOptions(resolvedTemplate) or {}
        if type(TouchLootProfileSettings) == "function" then
          TouchLootProfileSettings(profile)
        end
        return true
      elseif resolvedAction == "ROLL_OPTION_ADD" then
        local idx = math.max(1, tonumber(args[1]) or 1)
        profile.settings.rollOptions = type(profile.settings.rollOptions) == "table" and profile.settings.rollOptions or {}
        local option = {
          label = trim(args[2]),
          key = trim(args[3]),
          color = DecodeRollOptionColor(args[4]),
          icon = trim(args[5]) ~= "" and trim(args[5]) or nil,
          pointBehavior = trim(args[6]),
          popupSection = trim(args[7]),
        }
        table.insert(profile.settings.rollOptions, math.min(idx, #profile.settings.rollOptions + 1), option)
        profile.settings.rollOptions = type(NormalizeLootRollOptions) == "function" and NormalizeLootRollOptions(profile.settings.rollOptions) or profile.settings.rollOptions
        profile.settings.rollTemplate = CUSTOM_LOOT_ROLL_TEMPLATE
        if type(TouchLootProfileSettings) == "function" then
          TouchLootProfileSettings(profile)
        end
        return true
      elseif resolvedAction == "ROLL_OPTION_UPDATE" then
        local idx = tonumber(args[1])
        local options = type(profile.settings.rollOptions) == "table" and profile.settings.rollOptions or {}
        if not idx or idx < 1 or idx > #options then
          return false, "Roll option not found."
        end
        local option = options[idx]
        option.label = trim(args[2])
        option.key = trim(args[3])
        option.color = DecodeRollOptionColor(args[4])
        option.icon = trim(args[5]) ~= "" and trim(args[5]) or nil
        option.pointBehavior = trim(args[6])
        option.popupSection = trim(args[7])
        profile.settings.rollOptions = type(NormalizeLootRollOptions) == "function" and NormalizeLootRollOptions(options) or options
        profile.settings.rollTemplate = CUSTOM_LOOT_ROLL_TEMPLATE
        if type(TouchLootProfileSettings) == "function" then
          TouchLootProfileSettings(profile)
        end
        return true
      elseif resolvedAction == "ROLL_OPTION_MOVE" then
        local fromIndex = tonumber(args[1])
        local toIndex = tonumber(args[2])
        local options = type(profile.settings.rollOptions) == "table" and profile.settings.rollOptions or {}
        if not fromIndex or not toIndex or fromIndex < 1 or fromIndex > #options or toIndex < 1 or toIndex > #options then
          return false, "Roll option move is invalid."
        end
        local option = table.remove(options, fromIndex)
        table.insert(options, toIndex, option)
        profile.settings.rollTemplate = CUSTOM_LOOT_ROLL_TEMPLATE
        if type(TouchLootProfileSettings) == "function" then
          TouchLootProfileSettings(profile)
        end
        return true
      elseif resolvedAction == "ROLL_OPTION_REMOVE" then
        local idx = tonumber(args[1])
        local options = type(profile.settings.rollOptions) == "table" and profile.settings.rollOptions or {}
        if not idx or idx < 1 or idx > #options or #options <= 1 then
          return false, "Roll option remove is invalid."
        end
        table.remove(options, idx)
        profile.settings.rollTemplate = CUSTOM_LOOT_ROLL_TEMPLATE
        if type(TouchLootProfileSettings) == "function" then
          TouchLootProfileSettings(profile)
        end
        return true
      elseif resolvedAction == "POINT_MODE" then
        profile.settings.pointMode = type(NormalizePointMode) == "function" and NormalizePointMode(args[1]) or trim(args[1])
        if type(EnsureLidTableRows) == "function" then
          EnsureLidTableRows(profile.settings)
        end
        if type(TouchLootProfileSettings) == "function" then
          TouchLootProfileSettings(profile)
        end
        return true
      elseif resolvedAction == "LID_TABLE_ROW" then
        local rows = type(EnsureLidTableRows) == "function" and EnsureLidTableRows(profile.settings) or {}
        local idx = tonumber(args[1])
        if not idx or idx < 1 or idx > 15 then
          return false, "LidTable row not found."
        end
        local row = rows[idx]
        row.points = tonumber(args[2]) or idx
        row.itemLevel = trim(args[3]) ~= "" and tonumber(args[3]) or nil
        row.setPiecePoints = trim(args[4]) ~= "" and tonumber(args[4]) or nil
        row.offSpecPoints = trim(args[5]) ~= "" and tonumber(args[5]) or nil
        row.transmogPoints = trim(args[6]) ~= "" and tonumber(args[6]) or nil
        row.disenchantPoints = trim(args[7]) ~= "" and tonumber(args[7]) or nil
        if type(TouchLootProfileSettings) == "function" then
          TouchLootProfileSettings(profile)
        end
        return true
      elseif resolvedAction == "POINT_RULE_ADD" then
        profile.settings.pointRules = type(profile.settings.pointRules) == "table" and profile.settings.pointRules or {}
        profile.settings.pointRules[#profile.settings.pointRules + 1] = {
          mode = trim(args[1]) == "item" and "item" or "itemLevel",
          itemLevel = tonumber(args[2]),
          points = tonumber(args[3]) or 0,
          itemID = type(ExtractItemID) == "function" and ExtractItemID(args[4]) or nil,
          itemName = trim(args[5]),
          itemLink = trim(args[6]),
        }
        if type(TouchLootProfileSettings) == "function" then
          TouchLootProfileSettings(profile)
        end
        return true
      elseif resolvedAction == "POINT_RULE_REMOVE" then
        local idx = tonumber(args[1])
        local rules = type(profile.settings.pointRules) == "table" and profile.settings.pointRules or {}
        if not idx or idx < 1 or idx > #rules then
          return false, "Point rule not found."
        end
        table.remove(rules, idx)
        if type(TouchLootProfileSettings) == "function" then
          TouchLootProfileSettings(profile)
        end
        return true
      elseif resolvedAction == "ROLE_SET" then
        local targetKey = trim(args[1])
        local role = trim(args[2])
        if skipAccessCheck then
          local permissions = type(EnsureLootProfilePermissionState) == "function" and EnsureLootProfilePermissionState(profile) or nil
          if targetKey == "" then
            return false, "Character-Realm is required."
          end
          if type(permissions) ~= "table" then
            return false, "Permission state is unavailable."
          end
          if trim(permissions.master) ~= "" and string.lower(trim(permissions.master)) == string.lower(targetKey) then
            return false, "The Master role cannot be changed."
          end
          if type(SetLootProfilePermissionMember) ~= "function" or type(NormalizeLootProfileRole) ~= "function" then
            return false, "Role update API is unavailable."
          end
          SetLootProfilePermissionMember(permissions, targetKey, NormalizeLootProfileRole(role))
          if type(TouchLootProfilePermissions) == "function" then
            TouchLootProfilePermissions(profile)
          end
          return true
        end
        if type(SetLootProfileMemberRole) ~= "function" then
          return false, "Role update API is unavailable."
        end
        return SetLootProfileMemberRole(name, targetKey, role, actorKey)
      elseif resolvedAction == "POLICY_SET" then
        if skipAccessCheck then
          profile.meta = type(profile.meta) == "table" and profile.meta or {}
          profile.meta.permissionPolicy = type(profile.meta.permissionPolicy) == "table" and profile.meta.permissionPolicy or { version = 1, roles = {} }
          profile.meta.permissionPolicy.roles = type(profile.meta.permissionPolicy.roles) == "table" and profile.meta.permissionPolicy.roles or {}
          local roleKey = string.upper(trim(args[1]))
          local permissionKey = trim(args[2])
          if roleKey == "" or permissionKey == "" then
            return false, "Permission policy delta is incomplete."
          end
          profile.meta.permissionPolicy.roles[roleKey] = type(profile.meta.permissionPolicy.roles[roleKey]) == "table" and profile.meta.permissionPolicy.roles[roleKey] or {}
          profile.meta.permissionPolicy.roles[roleKey][permissionKey] = args[3] == "1"
          if type(TouchLootProfilePermissions) == "function" then
            TouchLootProfilePermissions(profile)
          end
          return true
        end
        if type(SetLootProfilePermissionPolicyValue) ~= "function" then
          return false, "Permission policy API is unavailable."
        end
        return SetLootProfilePermissionPolicyValue(name, args[1], args[2], args[3] == "1", actorKey)
      elseif resolvedAction == "LEDGER_MANUAL_ADD" then
        return ApplyLootLedgerManualAddDelta(name, profile, args)
      elseif resolvedAction == "LEDGER_MANUAL_DELETE" then
        return ApplyLootLedgerManualDeleteDelta(name, profile, args)
      elseif resolvedAction == "LEDGER_MAIN_ALT_SET" then
        return ApplyLootLedgerMainAltDelta(profile, args)
      elseif resolvedAction == "LEDGER_NOTE_SET" then
        return ApplyLootLedgerNoteDelta(profile, args)
      elseif resolvedAction == "LEDGER_CHARACTER_DELETE" then
        return ApplyLootLedgerCharacterDeleteDelta(profile, args)
      end
      return false, "Unknown profile delta action."
    end)
  end

  return {
    BroadcastActiveProfileChange = BroadcastActiveProfileChange,
    BuildRollOptionDeltaArgs = BuildRollOptionDeltaArgs,
    BuildLidTableRowDeltaArgs = BuildLidTableRowDeltaArgs,
    ApplyIncomingLootProfileDelta = ApplyIncomingLootProfileDelta,
  }
end
