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_CreateInboundAdmissionHelpers_Impl = function(deps)
  deps = type(deps) == "table" and deps or {}
  local commPrefix = tostring(deps.CommPrefix 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 ParsePayload = deps.ParsePayload
  local ValidateCommProtocolFieldCount = deps.ValidateCommProtocolFieldCount
  local DispatchCommProtocolPayload = deps.DispatchCommProtocolPayload
  local GetMaxPayloadBytes = deps.GetMaxPayloadBytes
  local defaultInboundOps = type(deps.InboundOps) == "table" and deps.InboundOps or {}
  local defaultInboundRateLimiter = type(deps.InboundRateLimiter) == "table" and deps.InboundRateLimiter or nil
  local rateLimiterFailureLogged = false

  local function ProcessInboundAddonMessage(prefix, message, sender, opts)
    if prefix ~= commPrefix then
      return false, "ignored_prefix"
    end
    opts = type(opts) == "table" and opts or {}
    local telemetryOps = type(opts.inboundOps) == "table" and opts.inboundOps or defaultInboundOps
    local rateLimiter = type(opts.inboundRateLimiter) == "table" and opts.inboundRateLimiter or nil
    if rateLimiter == nil and opts.inboundOps == nil then
      rateLimiter = defaultInboundRateLimiter
    end
    local function record(operationName, ...)
      local operation = telemetryOps[operationName]
      if type(operation) == "function" then
        operation(...)
      end
    end

    local messageText = type(message) == "string" and message or tostring(message or "")
    if NormalizeCharacterKey(sender) == "" then
      record("record", "RAW", sender, #messageText)
      record("recordStage", "RAW", "received")
      record("recordRejected", "RAW", sender, "missing_incoming_sender")
      record("recordStage", "RAW", "rejected")
      return false, "missing_incoming_sender"
    end
    local maxPayloadBytes = type(GetMaxPayloadBytes) == "function" and GetMaxPayloadBytes() or 1024
    if #messageText > math.max(1, tonumber(maxPayloadBytes) or 1024) then
      record("record", "RAW", sender, #messageText)
      record("recordStage", "RAW", "received")
      record("recordRejected", "RAW", sender, "incoming_payload_exceeds_limit")
      record("recordStage", "RAW", "rejected")
      return false, "incoming_payload_exceeds_limit"
    end

    if type(ParsePayload) ~= "function"
      or type(ValidateCommProtocolFieldCount) ~= "function"
      or type(DispatchCommProtocolPayload) ~= "function"
    then
      record("recordRejected", "RAW", sender, "inbound_admission_unavailable")
      record("recordStage", "RAW", "rejected")
      return false, "inbound_admission_unavailable"
    end

    local fields = ParsePayload(messageText)
    local kind = TrimText(fields[1])
    record("record", kind, sender, #messageText)
    record("recordStage", kind ~= "" and kind or "UNKNOWN", "received")
    local fieldAccepted, fieldReason = ValidateCommProtocolFieldCount(kind, #fields)
    if not fieldAccepted then
      if fieldReason == "below_opcode_minimum" then
        record("recordContractRejected", kind)
      end
      record("recordRejected", kind ~= "" and kind or "UNKNOWN", sender, "incoming_payload_" .. tostring(fieldReason))
      record("recordStage", kind ~= "" and kind or "UNKNOWN", "rejected")
      return false, "incoming_payload_" .. tostring(fieldReason)
    end
    if kind == "" then
      record("recordRejected", "UNKNOWN", sender, "missing_incoming_opcode")
      record("recordStage", "UNKNOWN", "rejected")
      return false, "missing_incoming_opcode"
    end
    record("recordStage", kind, "contract")
    if type(rateLimiter) == "table" and type(rateLimiter.Check) == "function" then
      local rateCheckOk, rateAccepted, rateReason = pcall(rateLimiter.Check, sender, kind, #messageText)
      if not rateCheckOk then
        if opts.inboundOps == nil and not rateLimiterFailureLogged then
          rateLimiterFailureLogged = true
          local logError = rawget(_G, "LIDCOUNCIL_LogError")
          if type(logError) == "function" then
            pcall(logError, "Inbound rate limiter failed open: " .. tostring(rateAccepted))
          end
        end
      elseif not rateAccepted then
        record("recordRejected", kind, sender, rateReason)
        record("recordStage", kind, "rejected")
        return false, rateReason
      end
    end
    record("recordStage", kind, "admitted")

    local dispatched, dispatchReason, dispatchDetail = DispatchCommProtocolPayload(
      kind,
      fields,
      sender,
      opts.handlerRegistry,
      opts.activeSessionIdOverride
    )
    if not dispatched and dispatchReason == "unknown_opcode" then
      record("recordUnknownOpcode", kind)
      record("recordRejected", kind, sender, "unknown_incoming_opcode")
      record("recordStage", kind, "rejected")
    elseif not dispatched then
      if dispatchReason == "protocol_handler_error" then
        record("recordHandlerError", kind, sender, dispatchDetail)
      end
      record("recordRejected", kind, sender, dispatchReason)
      record("recordStage", kind, "rejected")
    else
      record("recordDispatched", kind, sender, #messageText)
      record("recordStage", kind, "dispatched")
    end
    return dispatched, dispatchReason, dispatchDetail
  end

  return {
    ProcessInboundAddonMessage = ProcessInboundAddonMessage,
  }
end
