import Foundation import HydraulophoneCore enum PlaybackRepeatMode: String, CaseIterable, Codable, Sendable { case off case all case one } /// Identity belongs to an occurrence in the queue, so repeated songs remain distinct. struct PlaybackQueueEntry: Identifiable, Codable, Equatable, Sendable { let id: UUID let song: Song init(song: Song) { id = UUID() self.song = song } private init(id: UUID, song: Song) { self.id = id self.song = song } func replacingSong(with song: Song) -> Self { Self(id: id, song: song) } } /// Session-only queue metadata. Media URLs are always resolved by the controller. struct PlaybackQueue: Sendable { private(set) var sourceEntries: [PlaybackQueueEntry] = [] private(set) var entries: [PlaybackQueueEntry] = [] private(set) var currentID: UUID? private(set) var isShuffling = false var repeatMode: PlaybackRepeatMode = .off var currentIndex: Int? { entries.firstIndex { $0.id == currentID } } var sourceIndex: Int? { sourceEntries.firstIndex { $0.id == currentID } } var currentEntry: PlaybackQueueEntry? { guard let currentIndex else { return nil } return entries[currentIndex] } static func restoring(_ archive: PlaybackQueueArchive) -> PlaybackQueue? { guard archive.isValid else { return nil } var queue = PlaybackQueue() queue.sourceEntries = archive.sourceEntries queue.entries = archive.entries queue.currentID = archive.currentID queue.isShuffling = archive.isShuffling queue.repeatMode = archive.repeatMode return queue } var archive: PlaybackQueueArchive { PlaybackQueueArchive( sourceEntries: sourceEntries, entries: entries, currentID: currentID, isShuffling: isShuffling, repeatMode: repeatMode) } var canAdvance: Bool { guard let currentIndex else { return false } return currentIndex + 1 < entries.count || repeatMode == .all } mutating func replace(with songs: [Song], startAt index: Int, shuffleAll: Bool = false) { sourceEntries = songs.map(PlaybackQueueEntry.init) entries = sourceEntries guard !entries.isEmpty else { currentID = nil return } if isShuffling, shuffleAll { entries.shuffle() currentID = entries.first?.id return } currentID = entries[min(max(index, 0), entries.count - 1)].id if isShuffling { shuffleUpcoming() } } mutating func setShuffle(_ enabled: Bool) { guard enabled != isShuffling else { return } isShuffling = enabled if enabled { shuffleUpcoming() } else { entries = sourceEntries } } mutating func append(_ song: Song, playNext: Bool = false) { let entry = PlaybackQueueEntry(song: song) if playNext, let currentIndex, let sourceIndex { entries.insert(entry, at: currentIndex + 1) sourceEntries.insert(entry, at: sourceIndex + 1) } else { sourceEntries.append(entry) entries.append(entry) } if currentID == nil { currentID = entry.id } } @discardableResult mutating func select(id: UUID) -> Bool { guard entries.contains(where: { $0.id == id }) else { return false } currentID = id return true } @discardableResult mutating func advance(automatically: Bool = false) -> Bool { guard let currentIndex else { return false } if automatically, repeatMode == .one { return true } if currentIndex + 1 < entries.count { currentID = entries[currentIndex + 1].id return true } guard repeatMode == .all else { return false } currentID = entries.first?.id return true } @discardableResult mutating func goBack() -> Bool { guard let currentIndex else { return false } if currentIndex > 0 { currentID = entries[currentIndex - 1].id } else if repeatMode == .all { currentID = entries.last?.id } return true } mutating func remove(id: UUID) { guard let index = entries.firstIndex(where: { $0.id == id }) else { return } entries.remove(at: index) sourceEntries.removeAll { $0.id == id } if currentID == id { currentID = entries.isEmpty ? nil : entries[min(index, entries.count - 1)].id } } mutating func clear() { sourceEntries.removeAll() entries.removeAll() currentID = nil } mutating func moveUpcoming(from offsets: IndexSet, to destination: Int) { guard let currentIndex else { return } let prefix = Array(entries.prefix(currentIndex + 1)) var upcoming = Array(entries.dropFirst(currentIndex + 1)) let valid = offsets.filter { upcoming.indices.contains($0) } guard !valid.isEmpty else { return } let moved = valid.map { upcoming[$0] } for index in valid.reversed() { upcoming.remove(at: index) } let target = min(max(0, destination - valid.filter { $0 < destination }.count), upcoming.count) upcoming.insert(contentsOf: moved, at: target) entries = prefix + upcoming // A deliberate order becomes the new unshuffled order, preserving history. sourceEntries = entries isShuffling = false } mutating func clearUpcoming() { guard let currentIndex else { return } let removed = Set(entries.dropFirst(currentIndex + 1).map(\.id)) entries.removeAll { removed.contains($0.id) } sourceEntries.removeAll { removed.contains($0.id) } } mutating func updateSongs(_ songs: [Song]) { let replacements = Dictionary(songs.map { ($0.id, $0) }, uniquingKeysWith: { _, last in last }) entries = entries.map { entry in replacements[entry.song.id].map { entry.replacingSong(with: $0) } ?? entry } sourceEntries = sourceEntries.map { entry in replacements[entry.song.id].map { entry.replacingSong(with: $0) } ?? entry } } private mutating func shuffleUpcoming() { guard let currentIndex else { return } // Preserve actual playback history and the active occurrence. let next = currentIndex + 1 entries = Array(entries.prefix(next)) + entries.dropFirst(next).shuffled() } } struct PlaybackQueueArchive: Codable, Sendable { static let schemaVersion = 1 static let maximumEntryCount = 1_000 let version: Int let sourceEntries: [PlaybackQueueEntry] let entries: [PlaybackQueueEntry] let currentID: UUID? let isShuffling: Bool let repeatMode: PlaybackRepeatMode init( sourceEntries: [PlaybackQueueEntry], entries: [PlaybackQueueEntry], currentID: UUID?, isShuffling: Bool, repeatMode: PlaybackRepeatMode ) { version = Self.schemaVersion self.sourceEntries = sourceEntries self.entries = entries self.currentID = currentID self.isShuffling = isShuffling self.repeatMode = repeatMode } var isValid: Bool { guard version == Self.schemaVersion, !entries.isEmpty, entries.count <= Self.maximumEntryCount, sourceEntries.count == entries.count, let currentID, entries.contains(where: { $0.id == currentID }) else { return false } let sourceIDs = Set(sourceEntries.map(\.id)) let playbackIDs = Set(entries.map(\.id)) guard sourceIDs.count == sourceEntries.count, sourceIDs == playbackIDs else { return false } return (sourceEntries + entries).allSatisfy { entry in !entry.song.id.isEmpty && entry.song.id.utf8.count <= 256 && entry.song.title.utf8.count <= 1_024 && entry.song.artist.utf8.count <= 1_024 && (entry.song.thumbnailURL.map(Self.isSafeThumbnailURL) ?? true) } } private static func isSafeThumbnailURL(_ url: URL) -> Bool { url.isFileURL || (url.scheme?.lowercased() == "https" && url.user == nil && url.password == nil) } }