-- This function merges the Packages folder from a DevModule into a shared
-- location. Until we have an improved package implementation, we need to
-- manually dedupe our libraries to cut down on bloat

local function dedupePackages(packages: Instance)
	local packageStorage = getPackageStorage()

	for _, package in ipairs(packages:GetChildren()) do
		if package ~= script and package:IsA("ModuleScript") then
			local version = getPackageVersion(package)

			local existingVersion: ModuleScript
			for _, otherPackage in ipairs(packageStorage:GetChildren()) do
				if otherPackage.Name:match(("^%s_"):format(package.Name)) and otherPackage:IsA("ModuleScript") then
					if version == getPackageVersion(otherPackage) then
						existingVersion = otherPackage
						break
					end
				end
			end

			if not existingVersion then
				local clone = package:Clone() :: ModuleScript
				clone.Parent = packageStorage
				clone.Name = ("%s_%s"):format(clone.Name, version)
				existingVersion = clone
			end

			-- Link the package with the existing version (which was either
			-- there previously, or is the one we just generated)
			local packageRef = constants.PACKAGE_REF:Clone()
			packageRef.Name = package.Name

			local packageObject = packageRef:FindFirstChild("package")
			if packageObject and packageObject:IsA("ObjectValue") then
				packageObject.Value = existingVersion
			end
			packageRef.Parent = package.Parent

			package:Destroy()

			log("link", ("%s <-> %s"):format(package.Name, existingVersion:GetFullName()))
		end
	end
end
