//
//  PlayableTrack.swift
//  DashSmash
//
//  Abstracts the two sources of "real song" audio that drive the tap-tempo
//  flow and Apple Music–backed gameplay: the MusicKit catalog (full Apple
//  Music search, requires MusicKit capability) and the device's local
//  library (MPMediaPickerController, works without MusicKit).
//

import Foundation
import MusicKit
import MediaPlayer

enum PlayableTrack {
    case appleMusicCatalog(Song)
    case library(MPMediaItem)
    case midi(MIDISong)

    var title: String {
        switch self {
        case .appleMusicCatalog(let s): return s.title
        case .library(let i):           return i.title ?? "Unknown"
        case .midi(let song):           return song.title
        }
    }

    var artistName: String {
        switch self {
        case .appleMusicCatalog(let s): return s.artistName
        case .library(let i):           return i.artist ?? "Unknown Artist"
        case .midi(let song):           return song.artistName
        }
    }

    /// Song length in seconds. Falls back to 90s if unknown.
    var duration: TimeInterval {
        switch self {
        case .appleMusicCatalog(let s): return s.duration ?? 90
        case .library(let i):           return i.playbackDuration
        case .midi(let song):           return song.parsedFile.durationSeconds
        }
    }

    /// Stable identifier used to persist the level and re-resolve the track
    /// on replay. Prefixed so we know which source to use on replay.
    var sourceID: String {
        switch self {
        case .appleMusicCatalog(let s): return "am:" + s.id.rawValue
        case .library(let i):           return "lib:\(i.persistentID)"
        case .midi(let song):           return song.sourceID
        }
    }
}
