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

INTERNAL_API.LIDCOUNCIL_CreateOutboundQueueCoalescingHelpers_Impl = function(deps)
  deps = type(deps) == "table" and deps or {}
  local TrimText = type(deps.TrimText) == "function" and deps.TrimText or function(value)
    return tostring(value or "")
  end
  local NormalizeCharacterKey = type(deps.NormalizeCharacterKey) == "function" and deps.NormalizeCharacterKey or TrimText
  local CanCoalesceDuplicateOutboundRequest = type(deps.CanCoalesceDuplicateOutboundRequest) == "function"
    and deps.CanCoalesceDuplicateOutboundRequest
    or function()
      return false
    end
  local AreEquivalentQueuedOutboundRequests = type(deps.AreEquivalentQueuedOutboundRequests) == "function"
    and deps.AreEquivalentQueuedOutboundRequests
    or function()
      return false
    end
  local BuildQueuedOutboundRequestCoverage = type(deps.BuildQueuedOutboundRequestCoverage) == "function"
    and deps.BuildQueuedOutboundRequestCoverage
    or function()
      return nil
    end
  local GetQueue = type(deps.GetQueue) == "function" and deps.GetQueue or function()
    return {}
  end
  local ReplaceQueue = type(deps.ReplaceQueue) == "function" and deps.ReplaceQueue or function()
  end

  local function ResolveQueuedOutboundRequestCoalescing(item, queue)
    if type(item) ~= "table" or not CanCoalesceDuplicateOutboundRequest(item.kind) then
      return false, {}
    end
    local resolvedQueue = type(queue) == "table" and queue or GetQueue()
    local supersededIndexes = {}
    for index, queued in ipairs(resolvedQueue) do
      if AreEquivalentQueuedOutboundRequests(queued, item) then
        return true, {}
      end
      local coverage = BuildQueuedOutboundRequestCoverage(queued, item)
      if type(coverage) == "table" then
        if coverage.replacementCoveredByExisting == true then
          return true, {}
        elseif coverage.existingCoveredByReplacement == true then
          supersededIndexes[#supersededIndexes + 1] = index
        end
      end
    end
    return false, supersededIndexes
  end

  local function CanReplaceQueuedOutboundStatePacket(kind)
    local resolvedKind = TrimText(kind)
    return resolvedKind == "PSTATE"
      or resolvedKind == "MEMBER"
      or resolvedKind == "LOCALAP"
      or resolvedKind == "APNOTICE"
      or resolvedKind == "START"
      or resolvedKind == "IACK"
      or resolvedKind == "JOIN"
      or resolvedKind == "JACK"
      or resolvedKind == "PSUB_STATE"
      or resolvedKind == "PSUBPATCH_STATE"
  end

  local function BuildQueuedOutboundStatePacketIdentity(item)
    if type(item) ~= "table" or not CanReplaceQueuedOutboundStatePacket(item.kind) then
      return ""
    end
    local metadata = type(item.metadata) == "table" and item.metadata or {}
    local sessionId = string.lower(TrimText(metadata.sessionId))
    local profileName = string.lower(TrimText(metadata.profileName))
    local stateKey = ""
    local resolvedKind = TrimText(item.kind)
    if resolvedKind == "PSTATE" then
      stateKey = NormalizeCharacterKey(metadata.actor)
    elseif resolvedKind == "PSUB_STATE" then
      local profileId = string.lower(TrimText(metadata.profileId))
      local domain = string.lower(TrimText(metadata.domain))
      local partIndex = math.max(0, tonumber(metadata.partIndex) or 0)
      if profileId == "" or domain == "" or partIndex <= 0 then
        return ""
      end
      stateKey = table.concat({ profileId, domain, tostring(partIndex) }, "|")
    elseif resolvedKind == "PSUBPATCH_STATE" then
      local profileId = string.lower(TrimText(metadata.profileId))
      local partIndex = math.max(0, tonumber(metadata.partIndex) or 0)
      if profileId == "" or partIndex <= 0 then
        return ""
      end
      stateKey = table.concat({ profileId, tostring(partIndex) }, "|")
    else
      stateKey = NormalizeCharacterKey(metadata.memberKey)
    end
    if sessionId == "" or profileName == "" or stateKey == "" then
      return ""
    end
    return string.lower(table.concat({
      resolvedKind,
      sessionId,
      profileName,
      stateKey,
    }, "|"))
  end

  local function ResolveQueuedOutboundStatePacketReplacement(item, queue)
    local replacementIdentity = BuildQueuedOutboundStatePacketIdentity(item)
    if replacementIdentity == "" then
      return {}
    end
    local resolvedQueue = type(queue) == "table" and queue or GetQueue()
    local supersededIndexes = {}
    local replacementKind = TrimText(item.kind)
    local replacementMetadata = type(item.metadata) == "table" and item.metadata or {}
    local replaceOlderPreciseSet = (replacementKind == "PSUB_STATE" or replacementKind == "PSUBPATCH_STATE")
      and math.max(0, tonumber(replacementMetadata.partIndex) or 0) == 1
      and TrimText(replacementMetadata.responseToken) ~= ""
    for index, queued in ipairs(resolvedQueue) do
      local queuedMetadata = type(queued) == "table" and type(queued.metadata) == "table" and queued.metadata or {}
      local replacesOlderPreciseSet = replaceOlderPreciseSet
        and TrimText(queuedMetadata.responseToken) ~= ""
        and TrimText(queuedMetadata.responseToken) ~= TrimText(replacementMetadata.responseToken)
        and string.lower(TrimText(queuedMetadata.sessionId)) == string.lower(TrimText(replacementMetadata.sessionId))
        and string.lower(TrimText(queuedMetadata.profileName)) == string.lower(TrimText(replacementMetadata.profileName))
        and string.lower(TrimText(queuedMetadata.profileId)) == string.lower(TrimText(replacementMetadata.profileId))
        and (replacementKind ~= "PSUB_STATE"
          or string.lower(TrimText(queuedMetadata.domain)) == string.lower(TrimText(replacementMetadata.domain)))
      if TrimText(type(queued) == "table" and queued.kind or "") == replacementKind
        and TrimText(type(queued) == "table" and queued.distribution or "") == TrimText(item.distribution)
        and NormalizeCharacterKey(type(queued) == "table" and queued.targetName or "") == NormalizeCharacterKey(item.targetName)
        and (BuildQueuedOutboundStatePacketIdentity(queued) == replacementIdentity or replacesOlderPreciseSet)
      then
        supersededIndexes[#supersededIndexes + 1] = index
      end
    end
    return supersededIndexes
  end

  local function RemoveQueuedOutboundRequestsByIndexes(indexes, queue)
    if type(indexes) ~= "table" or #indexes == 0 then
      return 0
    end
    local removeLookup = {}
    for _, index in ipairs(indexes) do
      local resolvedIndex = math.max(0, tonumber(index) or 0)
      if resolvedIndex > 0 then
        removeLookup[resolvedIndex] = true
      end
    end
    if next(removeLookup) == nil then
      return 0
    end

    local resolvedQueue = type(queue) == "table" and queue or GetQueue()
    local filteredQueue = {}
    local removedCount = 0
    for index, queued in ipairs(resolvedQueue) do
      if removeLookup[index] then
        removedCount = removedCount + 1
      else
        filteredQueue[#filteredQueue + 1] = queued
      end
    end
    if type(queue) == "table" then
      for index = #resolvedQueue, 1, -1 do
        resolvedQueue[index] = nil
      end
      for index, queued in ipairs(filteredQueue) do
        resolvedQueue[index] = queued
      end
    else
      ReplaceQueue(filteredQueue)
    end
    return removedCount
  end

  return {
    ResolveQueuedOutboundRequestCoalescing = ResolveQueuedOutboundRequestCoalescing,
    ResolveQueuedOutboundStatePacketReplacement = ResolveQueuedOutboundStatePacketReplacement,
    RemoveQueuedOutboundRequestsByIndexes = RemoveQueuedOutboundRequestsByIndexes,
  }
end
