import Observation
import ShazamKit

@Observable
final class ShazamService {
    var isListening = false
    var matchedTitle: String?
    var matchedArtist: String?
    var errorMessage: String?

    private let session = SHManagedSession()
    private var listeningTask: Task<Void, Never>?

    func startListening() {
        guard !isListening else {
            stopListening()
            return
        }

        matchedTitle = nil
        matchedArtist = nil
        errorMessage = nil
        isListening = true

        listeningTask = Task {
            let result = await session.result()
            guard !Task.isCancelled else { return }
            switch result {
            case .match(let match):
                if let item = match.mediaItems.first {
                    matchedTitle = item.title
                    matchedArtist = item.artist
                }
            case .noMatch:
                errorMessage = "No match found. Try again in a quieter environment."
            case .error(let error, _):
                errorMessage = "Recognition failed: \(error.localizedDescription)"
            @unknown default:
                break
            }
            isListening = false
        }
    }

    func stopListening() {
        listeningTask?.cancel()
        listeningTask = nil
        session.cancel()
        isListening = false
    }

    func clearResult() {
        matchedTitle = nil
        matchedArtist = nil
        errorMessage = nil
    }
}
