Apple Script to create a (truly) random playlist based on other playlist(s)

-- CONFIG
set sourcePlaylists to {"Playlist#1", "Playlist#2", "etc..."}
set targetPlaylistName to "# Jukebox Journey"
set trackLimit to 100

tell application "Music"
	try
		set allTrackRefs to {} -- lijst met {playlistName, trackIndex, persistent ID}
		set seenIDs to {}
		
		-- Gather unique tracks from each playlist
		repeat with plName in sourcePlaylists
			if exists playlist plName then
				set pl to playlist plName
				set trackCount to count of tracks of pl
				repeat with i from 1 to trackCount
					set t to track i of pl
					try
						set pid to persistent ID of t
					on error
						set pid to ""
					end try
					
					if pid is not in seenIDs then
						set end of seenIDs to pid
						set end of allTrackRefs to {plName, i, pid}
					end if
				end repeat
			else
				display dialog "Playlist '" & plName & "' does not exist." buttons {"OK"}
				return
			end if
		end repeat
		
		set totalTracks to count of allTrackRefs
		if totalTracks < trackLimit then
			display dialog "Not enough unique tracks (" & totalTracks & ") to get a playlist of " & trackLimit & " tracks." buttons {"OK"}
			return
		end if
		
		-- Shuffle selection
		set pickedRefs to {}
		set pickedIDs to {}
		repeat while (count of pickedRefs) < trackLimit
			set idx to random number from 1 to totalTracks
			set candidateRef to item idx of allTrackRefs
			set candidatePID to item 3 of candidateRef
			if candidatePID is not in pickedIDs then
				set end of pickedRefs to candidateRef
				set end of pickedIDs to candidatePID
			end if
		end repeat
		
		-- Remove playlist if exists and create a new one
		if exists playlist targetPlaylistName then
			delete playlist targetPlaylistName
		end if
		set targetPlaylist to make new user playlist with properties {name:targetPlaylistName}
		
		-- Add tracks and prevent duplicates
		repeat with refItem in pickedRefs
			set plName to item 1 of refItem
			set trackIdx to item 2 of refItem
			set srcTrack to track trackIdx of playlist plName
			duplicate srcTrack to targetPlaylist
		end repeat
		
		-- Add stats to the description
		set currentDate to current date
		set formattedDate to (currentDate as string)
		
		set statsText to "🎶 Shuffle Playlist generated on: " & formattedDate & return & ¬
			"📦 Source(s): " & (count of sourcePlaylists) & return & ¬
			"🧠 Unique tracks available: " & totalTracks & return & ¬
			"🎯 Tracks selected: " & trackLimit
		
		set description of targetPlaylist to statsText
		
		play targetPlaylist
		reveal targetPlaylist
		
	on error errMsg
		display dialog "Error: " & errMsg buttons {"OK"}
	end try
end tell