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_CreateOutboundProfileTransferTelemetryHelpers_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 EnsureOutboundProfileTransfer = type(deps.EnsureOutboundProfileTransfer) == "function"
    and deps.EnsureOutboundProfileTransfer
    or function()
      return nil
    end

  local function IsOutboundProfileTransferTelemetryItem(item)
    local kind = TrimText(type(item) == "table" and item.kind or "")
    return kind == "PSYNC_START" or kind == "PSYNC_CHUNK" or kind == "PSYNC_END"
  end

  local function RecordOutboundProfileTransferTelemetry(item, eventName)
    if not IsOutboundProfileTransferTelemetryItem(item) then
      return nil
    end
    local metadata = type(item.metadata) == "table" and item.metadata or {}
    local transfer = EnsureOutboundProfileTransfer(metadata.transferId, metadata)
    if not transfer then
      return nil
    end
    local payloadBytes = #(tostring(item.payload or ""))
    if eventName == "attempted" then
      transfer.attemptedMessages = math.max(0, tonumber(transfer.attemptedMessages) or 0) + 1
      transfer.bytesAttempted = math.max(0, tonumber(transfer.bytesAttempted) or 0) + payloadBytes
    elseif eventName == "sent" then
      transfer.sentMessages = math.max(0, tonumber(transfer.sentMessages) or 0) + 1
      transfer.bytesSent = math.max(0, tonumber(transfer.bytesSent) or 0) + payloadBytes
    elseif eventName == "throttled" then
      transfer.throttledMessages = math.max(0, tonumber(transfer.throttledMessages) or 0) + 1
    elseif eventName == "failed" then
      transfer.failedMessages = math.max(0, tonumber(transfer.failedMessages) or 0) + 1
    end
    return transfer
  end

  return {
    IsOutboundProfileTransferTelemetryItem = IsOutboundProfileTransferTelemetryItem,
    RecordOutboundProfileTransferTelemetry = RecordOutboundProfileTransferTelemetry,
  }
end
