import Foundation /// Timing follows the beat grid; each card can request its own bar length. struct StudioSegment: Codable, Identifiable, Sendable { let start: Double let end: Double var scene: Int var bars: Int? = nil var id: Double { start } } enum StudioTimeline { static func sections(boundaries: [Double], bars: Int, scene: (_ index: Int, _ start: Double) -> Int) -> [StudioSegment] { zip(boundaries, boundaries.dropFirst()).enumerated().map { index, pair in StudioSegment(start: pair.0, end: pair.1, scene: scene(index, pair.0), bars: bars) } } /// Each scene is dealt once. Favorites lead; unused library scenes fill the tail. /// Return nil when uniqueness is impossible without changing the clip timing. static func randomizedScenes(current: [Int], favorites: [Int], available: [Int], allowRepeats: Bool = false) -> [Int]? { let availableSet = Set(available) let preferred = Set(favorites).intersection(availableSet) var choices = preferred.shuffled() + availableSet.subtracting(preferred).shuffled() guard !choices.isEmpty else { return nil } if allowRepeats && current.count > choices.count { var result: [Int] = [], bag = [Int]() for previous in current { if bag.isEmpty { bag = choices.shuffled() } let candidate = bag.firstIndex { $0 != result.last && $0 != previous } ?? bag.firstIndex { $0 != result.last } ?? bag.startIndex result.append(bag.remove(at: candidate)) } return result } guard current.count <= choices.count else { return nil } var result: [Int] = [] for (index, previous) in current.enumerated() { let favoritesLeft = choices.prefix(while: { preferred.contains($0) }).count // Reserve enough remaining slots to include every preferred scene. let requiredFavorites = favoritesLeft >= current.count - index let eligible = requiredFavorites ? 0.. Int? { guard !segments.isEmpty else { return nil } var low = 0, high = segments.count while low < high { let mid = (low + high) / 2; if segments[mid].start <= time { low = mid + 1 } else { high = mid } } return max(0, min(segments.count - 1, low - 1)) } static func valid(_ segments: [StudioSegment], sceneCount: Int) -> Bool { guard segments.count <= 10_000 else { return false } for (index, segment) in segments.enumerated() { guard segment.start.isFinite, segment.end.isFinite, segment.start >= 0, segment.end > segment.start, segment.bars.map({ $0 > 0 && $0 <= Int.max / 4 }) ?? true, (0..