```lua
-- bitstream.lua
local BitStream = {
	IO = require("samp.events.bitstream_io")
}

BitStream.new = raknetNewBitStream
BitStream.delete = raknetDeleteBitStream
BitStream.emul = raknetEmulPacketReceiveBitStream
BitStream.send = raknetSendBitStream
BitStream.getNumberOfUnreadBits = raknetBitStreamGetNumberOfUnreadBits

BitStream.IO.encodedString = (function()
	local this = {}
	local meta = {}

	function this.read(bs, size) return raknetBitStreamDecodeString(bs, size) end
	function this.write(bs, value) raknetBitStreamEncodeString(bs, value) end

	function meta:__index(size)
		return {
			read = function(bs) return raknetBitStreamDecodeString(bs, size) end,
			write = function(bs, value) raknetBitStreamEncodeString(bs, value) end
		}
	end

	return setmetatable(this, meta)
end)()

BitStream.IO.string = (function()
	local this = {}
	local meta = {}

	function this.read(bs, size) return raknetBitStreamReadString(bs, size) end
	function this.write(bs, value) raknetBitStreamWriteString(bs, value) end

	function meta:__index(size)
		return {
			read = function(bs) return raknetBitStreamReadString(bs, size) end,
			write = function(bs, value) raknetBitStreamWriteString(bs, value) end
		}
	end

	return setmetatable(this, meta)
end)()

BitStream.IO.byteArray = (function()
	local this = {}
	local meta = {}

	function this.read(bs, size)
		local t = {}
		for i = 1, size do
			t[i] = BitStream.IO.uint8.read(bs)
		end
		return t
	end

	function this.write(bs, value)
		for i, v in ipairs(bytes) do
			BitStream.IO.uint8.write(bs, v)
		end
	end

	function meta:__index(size)
		return {
			read = function(bs)
				local t = {}
				for i = 1, size do
					t[i] = BitStream.IO.uint8.read(bs)
				end
				return t
			end,
			write = function(bs, bytes)
				for i, v in ipairs(bytes) do
					BitStream.IO.uint8.write(bs, v)
				end
			end
		}
	end

	return setmetatable(this, meta)
end)()

BitStream.IO.maybeEncoded = (function()
	local this = {}

	function this.read(bs)
		local length = BitStream.IO.uint16.read(bs)
		local encoded = BitStream.IO.uint8.read(bs)
		return (encoded == 0) and BitStream.IO.string.read(bs, length) or BitStream.IO.encodedString.read(bs, length + 1)
	end

	function this.write(bs, str)
		BitStream.IO.uint16.write(bs, #str)
		BitStream.IO.uint8.write(bs, 0)
		BitStream.IO.string.write(bs, str)
	end

	return this
end)()

BitStream.IO.stringUnread = (function()
	local this = {}

	function this.read(bs)
		local size = math.ceil(BitStream.getNumberOfUnreadBits(bs) / 8)
		return (size > 0) and BitStream.IO.string.read(bs, size) or ""
	end

	function this.write(bs, value)
		BitStream.IO.string.write(bs, value)
	end

	return this
end)()

return BitStream
```
```lua
-- core.lua
local samp = require("samp.events")
local BitStream = require("arizona-events.bitstream")

local PACKET_ID_ARIZONA_CEF = 220
local PACKET_ID_ARIZONA_CEF_EX = 221

local module = {}
module.INTERFACE = {}
module.INTERFACE.BitStream = BitStream

local packet_io_t = (function()
	local this = {}

	local function pair_read(bs, pair)
		if pair[1].read then
			return pair[1].read(bs)
		else
			local t = {}
			for _, jpair in ipairs(pair[1]) do
				t[(jpair[2])] = pair_read(bs, jpair)
			end
			return t
		end
	end

	local function pair_write(bs, pair, packet)
		if pair[1].write then
			pair[1].write(bs, packet[(pair[2])])
		else
			for _, jpair in ipairs(pair[1]) do
				pair_write(bs, jpair, packet[(pair[2])])
			end
		end
	end

	function this:read(bs, packet)
		if self.sizeof == 0 then
			local size = math.ceil(BitStream.getNumberOfUnreadBits(bs) / 8)
			packet.bytes = {}
			for i = 1, size do
				packet.bytes[i] = BitStream.IO.uint8.read(bs)
			end
		else
			for _, pair in ipairs(self.struct) do
				packet[(pair[2])] = pair_read(bs, pair)
			end
		end
	end
 
	function this:write(bs, packet)
		if self.sizeof == 0 then
			for i, v in ipairs(packet.bytes) do
				BitStream.IO.uint8.write(v)
			end
		else
			for _, pair in ipairs(self.struct) do
				pair_write(bs, pair, packet)
			end
		end
	end
	
	local function constructor(_, event, struct)
		local t = {}
		t.event = event
		t.struct = struct or {}
		t.sizeof = #t.struct
		return setmetatable(t, { __index = this })
	end

	return setmetatable(this, { __call = constructor })
end)()

local packet_pool = (function()
	local this = {}
	this.data = {}

	function this:push(id, event, base)
		self.data[event] = { id = id, base = base }
	end

	function this:get(event)
		return self.data[event]
	end

	return this
end)()

local function create_packet_handler(id, first_field, default_event, samp_interface)
	local this = {}
	local meta = {}
	local pool = {}
	setmetatable(this, meta)

	this.id = id
	this.first_field = first_field
	this.default_io = packet_io_t(default_event)

	function this.read(bs)
		local packet = {}
		packet.id = this.first_field.read(bs)
		local packet_io = this[packet.id] or this.default_io
		packet_io:read(bs, packet)
		return packet_io.event, { packet }
	end

	function this.write(bs, data)
		local packet = data[1]
		local packet_io = this[packet.id] or this.default_io
		this.first_field.write(bs, packet.id)
		packet_io:write(bs, packet)
	end

	function meta:__newindex(k, v)
		local packet_io
		if v.event then
			packet_io = v
		else
			local event = v[1]
			table.remove(v, 1)
			packet_io = packet_io_t(event, v)
		end
		rawset(self, k, packet_io)
		table.insert(pool, packet_io.event)
		packet_pool:push(k, packet_io.event, this)
	end

	this[-1] = this.default_io

	samp_interface[id] = { pool, this.read, this.write }

	return this
end

module.INTERFACE.INCOMING    = create_packet_handler(PACKET_ID_ARIZONA_CEF, BitStream.IO.uint8, "onArizonaAnyIn", samp.INTERFACE.INCOMING_PACKETS)
module.INTERFACE.OUTGOING    = create_packet_handler(PACKET_ID_ARIZONA_CEF, BitStream.IO.uint8, "onArizonaAnyOut", samp.INTERFACE.OUTCOMING_PACKETS)
module.INTERFACE.INCOMING_EX = create_packet_handler(PACKET_ID_ARIZONA_CEF_EX, BitStream.IO.uint16, "onArizonaAnyInEx", samp.INTERFACE.INCOMING_PACKETS)
module.INTERFACE.OUTGOING_EX = create_packet_handler(PACKET_ID_ARIZONA_CEF_EX, BitStream.IO.uint16, "onArizonaAnyOutEx", samp.INTERFACE.OUTCOMING_PACKETS)

function module.emul(event, packet)
	local t = packet_pool:get(event)
	if t then
		packet.id = packet.id or t.id
		local bs = BitStream.new()
		BitStream.IO.uint8.write(bs, t.base.id)
		t.base.write(bs, { packet })
		BitStream.emul(t.io.base_id, bs)
		BitStream.delete(bs)
	end
end

function module.send(event, packet)
	local t = packet_pool:get(event)
	if t then
		packet.id = packet.id or t.id
		local bs = BitStream.new()
		BitStream.IO.uint8.write(bs, t.base.id)
		t.base.write(bs, { packet })
		BitStream.send(bs)
		BitStream.delete(bs)
	end
end

return module
```
```lua
-- init.lua
local module = require("arizona-events.core")

local IO          = module.INTERFACE.BitStream.IO
local INCOMING    = module.INTERFACE.INCOMING
local OUTGOING    = module.INTERFACE.OUTGOING
local INCOMING_EX = module.INTERFACE.INCOMING_EX
local OUTGOING_EX = module.INTERFACE.OUTGOING_EX

INCOMING[10] = {
	"onArizonaLoadJs", 
	{ IO.byteArray[16], "_unknown" }, 
	{ IO.maybeEncoded,  "js" }, 
	{ IO.maybeEncoded,  "any" },
	{ IO.uint32,        "server_id" }
}

INCOMING[17] = {
	"onArizonaDisplay",
	{ IO.uint32,       "server_id" },
	{ IO.maybeEncoded, "text"}
}

INCOMING[25] = {
	"onArizonaToggleCursor",
	{ IO.uint32, "_unknown1" },
	{ IO.bool8,  "status" },
	{ IO.uint16, "_unknown2" }
}

INCOMING[108] = {
	"onArizonaSwitchChatState",
	{ IO.uint32, "player_id" },
	{ IO.bool,   "is_open" }
}

INCOMING[153] = {
	"onArizonaSetVehicleNumberPlate",
	{ IO.uint16,  "vehicle_id" },
	{ IO.uint8,   "plate_type" },
	{ IO.string8, "plate_text" }
}

INCOMING[155] = {
	"onArizonaSetPlayerAttachedObject",
	{ IO.uint16, "player_id" },
	{ IO.int32,  "index" },
	{ IO.bool,   "create" },
	{
		{
			{ IO.int32,    "model_id" },
			{ IO.int32,    "bone" },
			{ IO.vector3d, "offset" },
			{ IO.vector3d, "rotation" },
			{ IO.vector3d, "scale" },
			{ IO.int32,    "color1" },
			{ IO.int32,    "color2" }
		}, "object"
	}
}

INCOMING[165] = {
	"onArizonaLoadBinary",
	{ IO.string8, "text" }
}

INCOMING[172] = {
	"onArizonaSetCurrentTask",
	{ IO.uint8,        "_unused" },
	{ IO.string8,      "text" },
	{ IO.stringUnread, "emoji" }
}

OUTGOING[0] = {
	"onArizonaSendKey",
	{ IO.uint8, "key" },
	{ IO.uint8, "_unknown" }
}

OUTGOING[1] = {
	"onArizonaSendSwitchChatState",
	{ IO.bool, "is_open" }
}

OUTGOING[18] = {
	"onArizonaSend",
	{ IO.string16, "text" },
	{ IO.uint32,   "server_id" }
}

OUTGOING[38] = {
	"onArizonaSendHash",
	{ IO.string[64], "hash" }
}

OUTGOING[140] = {
	"onArizonaSendClientJoin",
	{ IO.string16, "text" }
}

INCOMING_EX[50] = {
	"onArizonaBotStreamIn",
	{ IO.uint16,       "bot_id" },
	{ IO.int16,        "model_id" },
	{ IO.vector3d,     "position" },
	{ IO.float,        "rotation" },
	{ IO.bool,         "_pading" },
	{ IO.float,        "health" },
	{ IO.float,        "armour" },
	{ IO.byteArray[3], "_unknown1" },
	{
		{
			{ IO.int32, "color" },
			{ IO.string32, "text" }
		},
		"nametag_1"
	},
	{ IO.byteArray[1],  "_unknown2" },
	{
		{
			{ IO.int32, "color" },
			{ IO.string32, "text" }
		},
		"nametag_2"
	},
	{ IO.byteArray[7],  "_unknown3" }
}

INCOMING_EX[51] = {
	"onArizonaBotStreamOut",
	{ IO.uint16, "bot_id" }
}

INCOMING_EX[66] = {
	"onArizonaSetBotPos",
	{ IO.uint16, "bot_id" },
	{ IO.vector3d, "position" }
}

INCOMING_EX[67] = {
	"onArizonaSetBotTargetPos",
	{ IO.uint16,       "bot_id" },
	{ IO.vector3d,     "position" },
	{ IO.byteArray[6], "_unknown" }
}

INCOMING_EX[69] = {
	"onArizonaApplyBotAnimation",
	{ IO.uint16,       "bot_id" },
	{ IO.string32,     "anim_lib" },
	{ IO.string32,     "anim_name" },
	{ IO.byteArray[9], "_unknown" }
}

INCOMING_EX[81] = {
	"onArizonaBotEnterVehicle",
	{ IO.uint16,       "bot_id" },
	{ IO.uint16,       "vehicle_id" },
	{ IO.byteArray[6], "_unknown" }
}

INCOMING_EX[84] = {
	"onArizonaBotExitVehicle",
	{ IO.uint16, "bot_id" }
}

INCOMING_EX[85] = {
	"onArizonaBotChatBubble",
	{ IO.uint16,   "bot_id" },
	{ IO.string32, "text" },
	{ IO.int32,    "color" },
	{ IO.float,    "distance" },
	{ IO.int32,    "duration" }
}

OUTGOING_EX[73] = {
	"onArizonaSendBotDamage",
	{ IO.bool,   "give_or_take" },
	{ IO.uint16, "bot_id" },
	{ IO.float,  "damage" },
	{ IO.int32,  "weapon" },
	{ IO.int32,  "bodypart" },
	{ IO.uint16, "_unknown" },
	{ IO.uint16, "player_id" }
}

return module
```
Пожалуйста, полностью переработай и перепиши следующий Lua-код, внедрив в него основные принципа разработки программного обеспечения:

- SOLID (Single Responsibility, Open/Closed, Liskov Substitution, Interface Segregation, Dependency Inversion)
- DRY (Don't Repeat Yourself)
- KISS (Keep It Simple, Stupid)
- YAGNI (You Aren't Gonna Need It)
- EAFP (Easier to Ask Forgiveness than Permission)
- Использование локальных переменных вместо глобальных
- Организация кода в модули и функции
- Чистота, читаемость и расширяемость кода
- Обработка ошибок через pcall/xpcall или другие подходящие механизмы
- Использование метатаблиц (если это уместно) для реализации ООП-подхода
- Поясни свои изменения комментариями в коде

Ниже предоставляю исходный Lua-код. Сделай его более надежным, масштабируемым и читаемым, руководствуясь этими принципами.

```lua
-- здесь вставляется исходный код --