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

  local TrimText = deps.TrimText
  local RootDB = deps.RootDB
  local EnsureLootLedgerMeta = deps.EnsureLootLedgerMeta
  local TouchLootProfile = deps.TouchLootProfile
  local GetCharacterKey = deps.GetCharacterKey
  local GetLootProfile = deps.GetLootProfile
  local GetActiveLootSession = deps.GetActiveLootSession

  local LOOT_PROFILE_ROLE_MASTER = "MASTER"
  local LOOT_PROFILE_ROLE_COUNCIL = "COUNCIL"
  local LOOT_PROFILE_ROLE_RAIDER = "RAIDER"
  local LOOT_PROFILE_ROLE_SESSION_HOST = "SESSION_HOST"
  local LOOT_PROFILE_POLICY_VERSION = 1
  local LOOT_PROFILE_PERMISSION_KEYS = {
    "canManageRoles",
    "canManageRights",
    "canEditRaidSettings",
    "canEditRollSettings",
    "canEditPointSettings",
    "canStartSession",
    "canManageSession",
    "canOpenLiveBoard",
    "canVote",
    "canAssignLoot",
    "canEditLootList",
    "canEditManualPoints",
    "canDeleteLootListCharacter",
    "canEditMainAlt",
    "canEditNotes",
    "canDeleteProfile",
  }

  local DEFAULT_ROLE_ACCESS = {
    MASTER = {
      canDeleteProfile = true,
      canManageRoles = true,
      canManageRights = true,
      canTransferMaster = true,
      canStartSession = true,
      canManageSession = true,
      canOpenLiveBoard = true,
      canVote = true,
      canAssignLoot = true,
      canEditLootList = true,
      canEditManualPoints = true,
      canDeleteLootListCharacter = true,
      canEditMainAlt = true,
      canEditNotes = true,
      canEditRaidSettings = true,
      canEditRollSettings = true,
      canEditPointSettings = true,
    },
    COUNCIL = {
      canDeleteProfile = true,
      canManageRoles = true,
      canManageRights = false,
      canTransferMaster = false,
      canStartSession = true,
      canManageSession = true,
      canOpenLiveBoard = true,
      canVote = true,
      canAssignLoot = false,
      canEditLootList = true,
      canEditManualPoints = true,
      canDeleteLootListCharacter = true,
      canEditMainAlt = true,
      canEditNotes = true,
      canEditRaidSettings = true,
      canEditRollSettings = true,
      canEditPointSettings = true,
    },
    RAIDER = {
      canDeleteProfile = true,
      canManageRoles = false,
      canManageRights = false,
      canTransferMaster = false,
      canStartSession = false,
      canManageSession = false,
      canOpenLiveBoard = false,
      canVote = false,
      canAssignLoot = false,
      canEditLootList = false,
      canEditManualPoints = false,
      canDeleteLootListCharacter = false,
      canEditMainAlt = false,
      canEditNotes = false,
      canEditRaidSettings = false,
      canEditRollSettings = false,
      canEditPointSettings = false,
    },
    SESSION_HOST = {
      canDeleteProfile = true,
      canManageRoles = true,
      canManageRights = false,
      canTransferMaster = false,
      canStartSession = true,
      canManageSession = true,
      canOpenLiveBoard = true,
      canVote = true,
      canAssignLoot = true,
      canEditLootList = true,
      canEditManualPoints = true,
      canDeleteLootListCharacter = true,
      canEditMainAlt = true,
      canEditNotes = true,
      canEditRaidSettings = true,
      canEditRollSettings = true,
      canEditPointSettings = true,
    },
  }

  local LOCKED_ROLE_ACCESS = {
    COUNCIL = {
      canDeleteProfile = true,
      canOpenLiveBoard = true,
      canVote = true,
    },
    SESSION_HOST = {
      canDeleteProfile = true,
      canManageSession = true,
      canOpenLiveBoard = true,
      canVote = true,
      canAssignLoot = true,
    },
    RAIDER = {
      canDeleteProfile = true,
      canManageRights = false,
    },
  }

  local function NormalizeLootProfileRole(role)
    local resolvedRole = string.upper(TrimText(role))
    if resolvedRole == LOOT_PROFILE_ROLE_MASTER then
      return LOOT_PROFILE_ROLE_MASTER
    end
    if resolvedRole == LOOT_PROFILE_ROLE_SESSION_HOST then
      return LOOT_PROFILE_ROLE_SESSION_HOST
    end
    if resolvedRole == LOOT_PROFILE_ROLE_COUNCIL then
      return LOOT_PROFILE_ROLE_COUNCIL
    end
    return LOOT_PROFILE_ROLE_RAIDER
  end

  local function GetSimulationRoleOverride(name, characterKey)
    if TrimText(name) ~= "Simulation" then
      return nil
    end
    local selfKey = type(GetCharacterKey) == "function" and TrimText(GetCharacterKey() or "") or ""
    local resolvedCharacter = TrimText(characterKey)
    if selfKey == "" or resolvedCharacter == "" or string.lower(selfKey) ~= string.lower(resolvedCharacter) then
      return nil
    end
    local root = type(RootDB) == "function" and RootDB() or nil
    local ui = type(root) == "table" and type(root.ui) == "table" and root.ui or nil
    local storedRole = type(ui) == "table" and TrimText(ui.simulationRoleOverride or "") or ""
    if storedRole == "" then
      return nil
    end
    return NormalizeLootProfileRole(storedRole)
  end

  local function GetSimulationSessionHostOverride(name, characterKey)
    if TrimText(name) ~= "Simulation" then
      return false
    end
    local selfKey = type(GetCharacterKey) == "function" and TrimText(GetCharacterKey() or "") or ""
    local resolvedCharacter = TrimText(characterKey)
    if selfKey == "" or resolvedCharacter == "" or string.lower(selfKey) ~= string.lower(resolvedCharacter) then
      return false
    end
    local root = type(RootDB) == "function" and RootDB() or nil
    local ui = type(root) == "table" and type(root.ui) == "table" and root.ui or nil
    return type(ui) == "table" and ui.simulationSessionHostOverride and true or false
  end

  local GetLootProfileRoleLocal
  local GetLootProfileAccessInfo
  local EnsureLootProfilePermissionState
  local TouchPermissionState

  local function ResolveEffectiveLootProfileRole(name, profile, characterKey)
    local resolvedCharacter = TrimText(characterKey)
    local role = GetLootProfileRoleLocal(profile, resolvedCharacter)
    local overrideRole = GetSimulationRoleOverride(name, resolvedCharacter)
    if overrideRole ~= nil then
      return overrideRole
    end
    return role
  end

  local function FindLootProfilePermissionMemberKey(permissions, characterKey)
    permissions = type(permissions) == "table" and permissions or {}
    local members = type(permissions.members) == "table" and permissions.members or {}
    local resolvedKey = TrimText(characterKey)
    if resolvedKey == "" then
      return nil
    end
    if members[resolvedKey] ~= nil then
      return resolvedKey
    end
    local needle = string.lower(resolvedKey)
    for storedKey in pairs(members) do
      if string.lower(tostring(storedKey or "")) == needle then
        return storedKey
      end
    end
    return nil
  end

  local function RemoveLootProfilePermissionMember(permissions, characterKey)
    permissions = type(permissions) == "table" and permissions or {}
    local members = type(permissions.members) == "table" and permissions.members or {}
    local storedKey = FindLootProfilePermissionMemberKey(permissions, characterKey)
    if storedKey then
      members[storedKey] = nil
      return true
    end
    return false
  end

  local function SetLootProfilePermissionMember(permissions, characterKey, role)
    permissions = type(permissions) == "table" and permissions or {}
    permissions.members = type(permissions.members) == "table" and permissions.members or {}
    local resolvedKey = TrimText(characterKey)
    if resolvedKey == "" then
      return false
    end
    if TrimText(permissions.master) ~= "" and string.lower(tostring(permissions.master)) == string.lower(resolvedKey) then
      RemoveLootProfilePermissionMember(permissions, resolvedKey)
      return true
    end
    RemoveLootProfilePermissionMember(permissions, resolvedKey)
    permissions.members[resolvedKey] = NormalizeLootProfileRole(role)
    if permissions.members[resolvedKey] == LOOT_PROFILE_ROLE_MASTER then
      permissions.members[resolvedKey] = LOOT_PROFILE_ROLE_COUNCIL
    end
    return true
  end

  local function GetLatestLootProfileSessionHost(profile)
    if type(profile) ~= "table" or type(profile.sessions) ~= "table" then
      return ""
    end

    local latestHost = ""
    local latestStartedAt = -1
    for _, session in ipairs(profile.sessions) do
      if type(session) == "table" then
        local startedAt = tonumber(session.startedAt) or 0
        local host = TrimText(session.host)
        if host ~= "" and startedAt >= latestStartedAt then
          latestStartedAt = startedAt
          latestHost = host
        end
      end
    end
    return latestHost
  end

  local function NormalizeLootProfilePolicyRole(role)
    local normalizedRole = NormalizeLootProfileRole(role)
    return normalizedRole
  end

  local function GetLockedLootProfilePermissionValue(role, permissionKey)
    local normalizedRole = NormalizeLootProfilePolicyRole(role)
    local locks = LOCKED_ROLE_ACCESS[normalizedRole]
    if type(locks) == "table" and locks[permissionKey] ~= nil then
      return locks[permissionKey] and true or false
    end
    return nil
  end

  local function IsActiveLootSessionHost(profileName, characterKey)
    if type(GetActiveLootSession) ~= "function" then
      return false
    end
    local activeSession, activeProfileName = GetActiveLootSession()
    if type(activeSession) ~= "table" then
      return false
    end

    local resolvedProfileName = TrimText(profileName)
    local resolvedActiveProfileName = TrimText(activeProfileName)
    if resolvedProfileName ~= "" and resolvedActiveProfileName ~= "" and string.lower(resolvedProfileName) ~= string.lower(resolvedActiveProfileName) then
      return false
    end

    local host = TrimText(activeSession.host)
    local resolvedCharacter = TrimText(characterKey)
    return host ~= "" and resolvedCharacter ~= "" and string.lower(host) == string.lower(resolvedCharacter)
  end

  local function EnsureLootProfilePermissionPolicyState(profile)
    profile = type(profile) == "table" and profile or {}
    profile.meta = profile.meta or {}
    local stored = type(profile.meta.permissionPolicy) == "table" and profile.meta.permissionPolicy or {}
    local normalized = {
      version = LOOT_PROFILE_POLICY_VERSION,
      roles = {},
    }

    local function normalizeRolePolicy(roleKey)
      local storedRole = type(stored.roles) == "table" and stored.roles[roleKey] or nil
      local rolePolicy = {}
      for _, permissionKey in ipairs(LOOT_PROFILE_PERMISSION_KEYS) do
        local value = nil
        if type(storedRole) == "table" then
          value = storedRole[permissionKey]
        end
        if value ~= nil and GetLockedLootProfilePermissionValue(roleKey, permissionKey) == nil then
          rolePolicy[permissionKey] = value and true or false
        end
      end
      normalized.roles[roleKey] = rolePolicy
    end

    normalizeRolePolicy(LOOT_PROFILE_ROLE_COUNCIL)
    normalizeRolePolicy(LOOT_PROFILE_ROLE_SESSION_HOST)
    normalizeRolePolicy(LOOT_PROFILE_ROLE_RAIDER)

    profile.meta.permissionPolicy = normalized
    return normalized
  end

  local function BuildLootProfilePermissionRoleState(profile, role)
    local normalizedRole = NormalizeLootProfilePolicyRole(role)
    local defaults = DEFAULT_ROLE_ACCESS[normalizedRole] or DEFAULT_ROLE_ACCESS[LOOT_PROFILE_ROLE_RAIDER]
    local resolved = {}

    for _, permissionKey in ipairs(LOOT_PROFILE_PERMISSION_KEYS) do
      resolved[permissionKey] = defaults[permissionKey] and true or false
    end

    if normalizedRole ~= LOOT_PROFILE_ROLE_MASTER then
      local policy = EnsureLootProfilePermissionPolicyState(profile)
      local rolePolicy = type(policy.roles) == "table" and policy.roles[normalizedRole] or nil
      if type(rolePolicy) == "table" then
        for _, permissionKey in ipairs(LOOT_PROFILE_PERMISSION_KEYS) do
          if rolePolicy[permissionKey] ~= nil then
            resolved[permissionKey] = rolePolicy[permissionKey] and true or false
          end
        end
      end
    end

    local locks = LOCKED_ROLE_ACCESS[normalizedRole]
    if type(locks) == "table" then
      for _, permissionKey in ipairs(LOOT_PROFILE_PERMISSION_KEYS) do
        if locks[permissionKey] ~= nil then
          resolved[permissionKey] = locks[permissionKey] and true or false
        end
      end
    end

    return resolved
  end

  local function GetLootProfilePermissionPolicyValue(profile, role, permissionKey)
    local roleState = BuildLootProfilePermissionRoleState(profile, role)
    return roleState[permissionKey] and true or false
  end

  local function GetLootProfilePermissionPolicyRoleState(name, role)
    local profile = GetLootProfile(name)
    return BuildLootProfilePermissionRoleState(profile, role)
  end

  local function IsKnownPermissionKey(permissionKey)
    local needle = TrimText(permissionKey)
    for _, knownKey in ipairs(LOOT_PROFILE_PERMISSION_KEYS) do
      if knownKey == needle then
        return true
      end
    end
    return false
  end

  local function BuildLootProfileAccessInfo(profile, profileName, permissions, roleMode, characterKey)
    local normalizedRoleMode = NormalizeLootProfileRole(roleMode)
    local policyRole = NormalizeLootProfilePolicyRole(normalizedRoleMode)
    local roleState = BuildLootProfilePermissionRoleState(profile, policyRole)
    local access = {
      profileName = profileName,
      characterKey = TrimText(characterKey),
      role = policyRole,
      roleMode = normalizedRoleMode,
      policyRole = policyRole,
      masterKey = TrimText(permissions.master),
      canTransferMaster = policyRole == LOOT_PROFILE_ROLE_MASTER,
      canCopyProfile = true,
      canActivateProfile = true,
      canViewHistory = true,
      canViewSession = true,
      isSessionHost = normalizedRoleMode == LOOT_PROFILE_ROLE_SESSION_HOST,
    }

    for _, permissionKey in ipairs(LOOT_PROFILE_PERMISSION_KEYS) do
      access[permissionKey] = roleState[permissionKey] and true or false
    end

    access.canManageProfile =
      access.canManageRoles or
      access.canManageRights or
      access.canEditRaidSettings or
      access.canEditRollSettings or
      access.canEditPointSettings or
      access.canTransferMaster

    return access
  end

  local function GetLootProfileAccessInfoForRole(name, roleMode)
    local profile, profileName = GetLootProfile(name)
    local permissions = EnsureLootProfilePermissionState(profile)
    return BuildLootProfileAccessInfo(profile, profileName, permissions, roleMode, "")
  end

  local function SetLootProfilePermissionPolicyValue(name, role, permissionKey, enabled, actorCharacterKey)
    local profile = GetLootProfile(name)
    local permissions = EnsureLootProfilePermissionState(profile)
    local actorKey = TrimText(actorCharacterKey)
    if actorKey == "" and type(GetCharacterKey) == "function" then
      actorKey = TrimText(GetCharacterKey() or "")
    end
    local actorAccess = GetLootProfileAccessInfo(name, actorKey)
    if not (type(actorAccess) == "table" and actorAccess.canManageRights) then
      return false, "Only the Master can change permission policies."
    end

    local normalizedRole = NormalizeLootProfilePolicyRole(role)
    if normalizedRole == LOOT_PROFILE_ROLE_MASTER then
      return false, "Master permissions are fixed."
    end
    if not IsKnownPermissionKey(permissionKey) then
      return false, "Unknown permission key."
    end
    local lockedPermissionValue = GetLockedLootProfilePermissionValue(normalizedRole, permissionKey)
    if lockedPermissionValue ~= nil and lockedPermissionValue ~= (enabled and true or false) then
      if permissionKey == "canManageRights" then
        return false, "Denied. Manage Rights can only be granted to Session Host or Council."
      end
      if permissionKey == "canDeleteProfile" then
        return false, "Delete Local Profile Copy is fixed for every role. It only removes your local copy and is blocked while a session is active."
      end
      return false, "Denied. Revoking this right would eliminate the purpose of this role."
    end

    local policy = EnsureLootProfilePermissionPolicyState(profile)
    policy.roles[normalizedRole] = type(policy.roles[normalizedRole]) == "table" and policy.roles[normalizedRole] or {}
    local rolePolicy = policy.roles[normalizedRole]
    local defaultValue = (DEFAULT_ROLE_ACCESS[normalizedRole] or DEFAULT_ROLE_ACCESS[LOOT_PROFILE_ROLE_RAIDER])[permissionKey] and true or false
    local normalizedEnabled = enabled and true or false

    if normalizedEnabled == defaultValue then
      rolePolicy[permissionKey] = nil
    else
      rolePolicy[permissionKey] = normalizedEnabled
    end

    local hasAnyOverride = false
    for _, knownKey in ipairs(LOOT_PROFILE_PERMISSION_KEYS) do
      if rolePolicy[knownKey] ~= nil then
        hasAnyOverride = true
        break
      end
    end
    if not hasAnyOverride then
      policy.roles[normalizedRole] = {}
    end

    TouchPermissionState(profile)
    return true, GetLootProfilePermissionPolicyRoleState(name, normalizedRole)
  end

  local function ResetLootProfilePermissionPolicy(name, actorCharacterKey)
    local profile = GetLootProfile(name)
    local actorKey = TrimText(actorCharacterKey)
    if actorKey == "" and type(GetCharacterKey) == "function" then
      actorKey = TrimText(GetCharacterKey() or "")
    end
    local actorAccess = GetLootProfileAccessInfo(name, actorKey)
    if not (type(actorAccess) == "table" and actorAccess.canManageRights) then
      return false, "Only the Master can reset permission policies."
    end

    profile.meta = profile.meta or {}
    profile.meta.permissionPolicy = nil
    EnsureLootProfilePermissionPolicyState(profile)
    TouchPermissionState(profile)
    return true
  end

  local function BuildLootProfilePermissionPolicyRoleDiagnostics(profile, role)
    local normalizedRole = NormalizeLootProfilePolicyRole(role)
    local policy = EnsureLootProfilePermissionPolicyState(profile)
    local rolePolicy = type(policy.roles) == "table" and policy.roles[normalizedRole] or nil
    local overrides = {}
    local overrideCount = 0
    for _, permissionKey in ipairs(LOOT_PROFILE_PERMISSION_KEYS) do
      if type(rolePolicy) == "table" and rolePolicy[permissionKey] ~= nil then
        overrideCount = overrideCount + 1
        overrides[#overrides + 1] = string.format("%s=%s", permissionKey, rolePolicy[permissionKey] and "ON" or "OFF")
      end
    end
    return overrideCount, overrides
  end

  local function GetLootProfilePermissionPolicyDiagnostics(name)
    local profile, profileName = GetLootProfile(name)
    local permissions = EnsureLootProfilePermissionState(profile)
    local policy = EnsureLootProfilePermissionPolicyState(profile)
    local councilOverrideCount, councilOverrides = BuildLootProfilePermissionPolicyRoleDiagnostics(profile, LOOT_PROFILE_ROLE_COUNCIL)
    local sessionHostOverrideCount, sessionHostOverrides = BuildLootProfilePermissionPolicyRoleDiagnostics(profile, LOOT_PROFILE_ROLE_SESSION_HOST)
    local raiderOverrideCount, raiderOverrides = BuildLootProfilePermissionPolicyRoleDiagnostics(profile, LOOT_PROFILE_ROLE_RAIDER)
    return {
      profileName = profileName,
      masterKey = TrimText(permissions.master),
      version = math.max(0, tonumber(policy.version) or LOOT_PROFILE_POLICY_VERSION),
      hasOverrides = (councilOverrideCount + sessionHostOverrideCount + raiderOverrideCount) > 0,
      councilOverrideCount = councilOverrideCount,
      councilOverrides = councilOverrides,
      sessionHostOverrideCount = sessionHostOverrideCount,
      sessionHostOverrides = sessionHostOverrides,
      raiderOverrideCount = raiderOverrideCount,
      raiderOverrides = raiderOverrides,
    }
  end

  EnsureLootProfilePermissionState = function(profile, fallbackMasterKey)
    profile = type(profile) == "table" and profile or {}
    profile.meta = profile.meta or {}

    local stored = type(profile.meta.permissions) == "table" and profile.meta.permissions or {}
    local permissions = {
      master = TrimText(stored.master),
      members = {},
    }

    local preferredMaster = permissions.master
    if preferredMaster == "" then
      preferredMaster = TrimText(fallbackMasterKey)
    end
    if preferredMaster == "" then
      preferredMaster = TrimText(profile.meta.createdBy)
    end
    if preferredMaster == "" then
      preferredMaster = GetLatestLootProfileSessionHost(profile)
    end
    permissions.master = preferredMaster

    local storedMembers = type(stored.members) == "table" and stored.members or {}
    for memberKey, memberRole in pairs(storedMembers) do
      local resolvedKey = TrimText(memberKey)
      if resolvedKey ~= "" and string.lower(resolvedKey) ~= string.lower(permissions.master) then
        local normalizedRole = NormalizeLootProfileRole(memberRole)
        if normalizedRole == LOOT_PROFILE_ROLE_MASTER then
          normalizedRole = LOOT_PROFILE_ROLE_COUNCIL
        end
        permissions.members[resolvedKey] = normalizedRole
      end
    end

    if permissions.master ~= "" then
      RemoveLootProfilePermissionMember(permissions, permissions.master)
    end

    profile.meta.permissions = permissions
    if profile.meta.createdBy == nil and permissions.master ~= "" then
      profile.meta.createdBy = permissions.master
    end
    return permissions
  end

  GetLootProfileRoleLocal = function(profile, characterKey)
    local permissions = EnsureLootProfilePermissionState(profile)
    local resolvedKey = TrimText(characterKey)
    if resolvedKey == "" then
      return LOOT_PROFILE_ROLE_RAIDER
    end
    if TrimText(permissions.master) ~= "" and string.lower(tostring(permissions.master)) == string.lower(resolvedKey) then
      return LOOT_PROFILE_ROLE_MASTER
    end
    local storedKey = FindLootProfilePermissionMemberKey(permissions, resolvedKey)
    if storedKey then
      return NormalizeLootProfileRole(permissions.members[storedKey])
    end
    return LOOT_PROFILE_ROLE_RAIDER
  end

  local function IsLootProfileManagerRole(role)
    local normalizedRole = NormalizeLootProfileRole(role)
    return normalizedRole == LOOT_PROFILE_ROLE_MASTER or normalizedRole == LOOT_PROFILE_ROLE_COUNCIL
  end

  local function CollectLootProfileKnownCharacters(profile)
    local knownCharacters = {}
    local seen = {}

    local function addCharacter(characterKey)
      local resolvedKey = TrimText(characterKey)
      if resolvedKey == "" then
        return
      end
      local lowerKey = string.lower(resolvedKey)
      if seen[lowerKey] then
        return
      end
      seen[lowerKey] = true
      knownCharacters[#knownCharacters + 1] = resolvedKey
    end

    local permissions = EnsureLootProfilePermissionState(profile)
    addCharacter(permissions.master)
    for memberKey in pairs(permissions.members or {}) do
      addCharacter(memberKey)
    end
    for memberKey in pairs(profile.lootLedger or {}) do
      addCharacter(memberKey)
    end
    for memberKey in pairs(EnsureLootLedgerMeta(profile)) do
      addCharacter(memberKey)
    end
    for _, session in ipairs(profile.sessions or {}) do
      if type(session) == "table" then
        addCharacter(session.host)
        for memberKey, member in pairs(session.members or {}) do
          addCharacter(memberKey ~= "" and memberKey or (type(member) == "table" and member.name or ""))
        end
      end
    end

    table.sort(knownCharacters, function(a, b)
      return string.lower(tostring(a or "")) < string.lower(tostring(b or ""))
    end)
    return knownCharacters
  end

  function GetLootProfileRole(name, characterKey)
    local profile = GetLootProfile(name)
    local resolvedCharacter = TrimText(characterKey)
    if resolvedCharacter == "" and type(GetCharacterKey) == "function" then
      resolvedCharacter = TrimText(GetCharacterKey() or "")
    end
    return ResolveEffectiveLootProfileRole(name, profile, resolvedCharacter)
  end

  function GetLootProfileMaster(name)
    local profile = GetLootProfile(name)
    local permissions = EnsureLootProfilePermissionState(profile)
    return TrimText(permissions.master)
  end

  function GetLootProfileRoleEntries(name)
    local profile = GetLootProfile(name)
    local permissions = EnsureLootProfilePermissionState(profile)
    local rows = {}
    local rolePriority = {
      [LOOT_PROFILE_ROLE_MASTER] = 1,
      [LOOT_PROFILE_ROLE_COUNCIL] = 2,
      [LOOT_PROFILE_ROLE_RAIDER] = 3,
    }

    for _, characterKey in ipairs(CollectLootProfileKnownCharacters(profile)) do
      rows[#rows + 1] = {
        character = characterKey,
        role = GetLootProfileRoleLocal(profile, characterKey),
        isMaster = TrimText(permissions.master) ~= "" and string.lower(TrimText(permissions.master)) == string.lower(characterKey),
      }
    end

    table.sort(rows, function(a, b)
      local aPriority = tonumber(rolePriority[a.role]) or 99
      local bPriority = tonumber(rolePriority[b.role]) or 99
      if aPriority == bPriority then
        return string.lower(tostring(a.character or "")) < string.lower(tostring(b.character or ""))
      end
      return aPriority < bPriority
    end)

    return rows
  end

  function GetLootProfileAccessInfo(name, characterKey)
    local profile, profileName = GetLootProfile(name)
    local resolvedCharacter = TrimText(characterKey)
    if resolvedCharacter == "" and type(GetCharacterKey) == "function" then
      resolvedCharacter = TrimText(GetCharacterKey() or "")
    end

    local permissions = EnsureLootProfilePermissionState(profile)
    local role = ResolveEffectiveLootProfileRole(profileName, profile, resolvedCharacter)
    local roleMode = role
    if role ~= LOOT_PROFILE_ROLE_MASTER and (GetSimulationSessionHostOverride(profileName, resolvedCharacter) or IsActiveLootSessionHost(profileName, resolvedCharacter)) then
      roleMode = LOOT_PROFILE_ROLE_SESSION_HOST
    end
    return BuildLootProfileAccessInfo(profile, profileName, permissions, roleMode, resolvedCharacter)
  end

  function EnsureLootProfileMemberRole(name, characterKey, role)
    local profile = GetLootProfile(name)
    local permissions = EnsureLootProfilePermissionState(profile)
    local resolvedKey = TrimText(characterKey)
    if resolvedKey == "" then
      return false, "Character-Realm is required."
    end
    if TrimText(permissions.master) ~= "" and string.lower(TrimText(permissions.master)) == string.lower(resolvedKey) then
      return true, LOOT_PROFILE_ROLE_MASTER
    end
    local storedKey = FindLootProfilePermissionMemberKey(permissions, resolvedKey)
    if storedKey then
      return true, NormalizeLootProfileRole(permissions.members[storedKey])
    end
    SetLootProfilePermissionMember(permissions, resolvedKey, role or LOOT_PROFILE_ROLE_RAIDER)
    TouchPermissionState(profile)
    return true, GetLootProfileRoleLocal(profile, resolvedKey)
  end

  function SyncLootProfilePermissionState(name, masterKey, characterKey, role)
    local profile = GetLootProfile(name)
    local permissions = EnsureLootProfilePermissionState(profile, masterKey)
    local resolvedMaster = TrimText(masterKey)
    local changed = false

    if resolvedMaster ~= "" and string.lower(TrimText(permissions.master)) ~= string.lower(resolvedMaster) then
      permissions.master = resolvedMaster
      changed = true
    end
    if TrimText(permissions.master) ~= "" then
      changed = RemoveLootProfilePermissionMember(permissions, permissions.master) or changed
    end

    local resolvedCharacter = TrimText(characterKey)
    local resolvedRole = TrimText(role)
    if resolvedCharacter ~= "" and resolvedRole ~= "" then
      if TrimText(permissions.master) ~= "" and string.lower(TrimText(permissions.master)) == string.lower(resolvedCharacter) then
        changed = RemoveLootProfilePermissionMember(permissions, resolvedCharacter) or changed
      else
        local priorRole = GetLootProfileRoleLocal(profile, resolvedCharacter)
        SetLootProfilePermissionMember(permissions, resolvedCharacter, resolvedRole)
        changed = changed or (priorRole ~= GetLootProfileRoleLocal(profile, resolvedCharacter))
      end
    end

    if changed then
      TouchPermissionState(profile)
    end
    return true, GetLootProfileAccessInfo(name)
  end

  function SetLootProfileMemberRole(name, characterKey, role, actorCharacterKey)
    local profile = GetLootProfile(name)
    local permissions = EnsureLootProfilePermissionState(profile)
    local actorKey = TrimText(actorCharacterKey)
    if actorKey == "" and type(GetCharacterKey) == "function" then
      actorKey = TrimText(GetCharacterKey() or "")
    end
    local actorAccess = GetLootProfileAccessInfo(name, actorKey)
    local actorRole = GetLootProfileRoleLocal(profile, actorKey)
    if not (type(actorAccess) == "table" and actorAccess.canManageRights) then
      return false, "Only the Master can manage profile roles and rights."
    end

    local targetKey = TrimText(characterKey)
    if targetKey == "" then
      return false, "Character-Realm is required."
    end
    if TrimText(permissions.master) ~= "" and string.lower(TrimText(permissions.master)) == string.lower(targetKey) then
      return false, "The Master role cannot be changed."
    end
    if actorRole == LOOT_PROFILE_ROLE_COUNCIL and string.lower(actorKey) == string.lower(targetKey) then
      return false, "Council Members cannot change their own role."
    end

    local nextRole = NormalizeLootProfileRole(role)
    if nextRole == LOOT_PROFILE_ROLE_MASTER then
      return false, "Use Transfer Master to assign the Master role."
    end

    SetLootProfilePermissionMember(permissions, targetKey, nextRole)
    TouchPermissionState(profile)
    return true, nextRole
  end

  function TransferLootProfileMaster(name, characterKey, actorCharacterKey)
    local profile = GetLootProfile(name)
    local permissions = EnsureLootProfilePermissionState(profile)
    local actorKey = TrimText(actorCharacterKey)
    if actorKey == "" and type(GetCharacterKey) == "function" then
      actorKey = TrimText(GetCharacterKey() or "")
    end

    local actorAccess = GetLootProfileAccessInfo(name, actorKey)
    if not (type(actorAccess) == "table" and actorAccess.canTransferMaster) then
      return false, "Only the Master can transfer the Master role."
    end

    local targetKey = TrimText(characterKey)
    if targetKey == "" then
      return false, "Character-Realm is required."
    end
    if TrimText(permissions.master) ~= "" and string.lower(TrimText(permissions.master)) == string.lower(targetKey) then
      return false, "That character is already the Master."
    end

    local previousMaster = TrimText(permissions.master)
    permissions.master = targetKey
    RemoveLootProfilePermissionMember(permissions, targetKey)
    if previousMaster ~= "" then
      SetLootProfilePermissionMember(permissions, previousMaster, LOOT_PROFILE_ROLE_COUNCIL)
    end
    RemoveLootProfilePermissionMember(permissions, permissions.master)
    TouchPermissionState(profile)
    return true, targetKey, previousMaster
  end

  function SetSimulationRoleOverride(name, role)
    if TrimText(name) ~= "Simulation" then
      return false, "Role Simulation is only available for the Simulation profile."
    end

    local root = type(RootDB) == "function" and RootDB() or nil
    if type(root) ~= "table" then
      return false, "Simulation role storage is unavailable."
    end
    if type(root.profiles) ~= "table" or type(root.profiles.Simulation) ~= "table" then
      return false, "Simulation profile not found."
    end

    local requestedRole = string.upper(TrimText(role))
    local isSessionHostMode = requestedRole == "SESSION_HOST"
    local normalizedRole = isSessionHostMode and LOOT_PROFILE_ROLE_COUNCIL or NormalizeLootProfileRole(role)
    root.ui = type(root.ui) == "table" and root.ui or {}
    root.ui.simulationRoleOverride = normalizedRole
    root.ui.simulationSessionHostOverride = isSessionHostMode and true or false

    local profile = GetLootProfile(name)
    if type(profile) == "table" then
      TouchPermissionState(profile)
    end
    return true, isSessionHostMode and "SESSION_HOST" or normalizedRole
  end

  function GetSimulationRoleMode(name, characterKey)
    local resolvedCharacter = TrimText(characterKey)
    if resolvedCharacter == "" and type(GetCharacterKey) == "function" then
      resolvedCharacter = TrimText(GetCharacterKey() or "")
    end
    if GetSimulationSessionHostOverride(name, resolvedCharacter) then
      return "SESSION_HOST"
    end
    local overrideRole = GetSimulationRoleOverride(name, resolvedCharacter)
    if overrideRole ~= nil then
      return overrideRole
    end
    local root = type(RootDB) == "function" and RootDB() or nil
    local profileName = TrimText(name)
    if type(root) == "table" and (type(root.profiles) ~= "table" or type(root.profiles[profileName]) ~= "table") then
      return nil
    end
    local profile = GetLootProfile(name)
    return GetLootProfileRoleLocal(profile, resolvedCharacter)
  end

  TouchPermissionState = function(profile)
    if type(TouchLootProfile) == "function" then
      return TouchLootProfile(profile)
    end
  end

  return {
    NormalizeLootProfileRole = NormalizeLootProfileRole,
    GetSimulationRoleOverride = GetSimulationRoleOverride,
    GetSimulationSessionHostOverride = GetSimulationSessionHostOverride,
    GetSimulationRoleMode = GetSimulationRoleMode,
    ResolveEffectiveLootProfileRole = ResolveEffectiveLootProfileRole,
    RemoveLootProfilePermissionMember = RemoveLootProfilePermissionMember,
    SetLootProfilePermissionMember = SetLootProfilePermissionMember,
    EnsureLootProfilePermissionState = EnsureLootProfilePermissionState,
    GetLootProfileRoleLocal = GetLootProfileRoleLocal,
    IsLootProfileManagerRole = IsLootProfileManagerRole,
    CollectLootProfileKnownCharacters = CollectLootProfileKnownCharacters,
    GetLootProfileRole = GetLootProfileRole,
    GetLootProfileMaster = GetLootProfileMaster,
    GetLootProfileRoleEntries = GetLootProfileRoleEntries,
    GetLootProfileAccessInfo = GetLootProfileAccessInfo,
    GetLootProfileAccessInfoForRole = GetLootProfileAccessInfoForRole,
    GetLootProfilePermissionPolicyRoleState = GetLootProfilePermissionPolicyRoleState,
    GetLootProfilePermissionPolicyDiagnostics = GetLootProfilePermissionPolicyDiagnostics,
    SetLootProfilePermissionPolicyValue = SetLootProfilePermissionPolicyValue,
    ResetLootProfilePermissionPolicy = ResetLootProfilePermissionPolicy,
    EnsureLootProfileMemberRole = EnsureLootProfileMemberRole,
    SyncLootProfilePermissionState = SyncLootProfilePermissionState,
    SetLootProfileMemberRole = SetLootProfileMemberRole,
    TransferLootProfileMaster = TransferLootProfileMaster,
    SetSimulationRoleOverride = SetSimulationRoleOverride,
  }
end
