package com.keylightpiano.pianotimeline.data

import android.net.Uri

/**
 * Parses an incoming deep-link URL that points at a media file living next to
 * list.json, e.g.:
 *   https://timeline.keylightpiano.com/music/22.06.2026 - Sinatra - ... - 2.mp3
 *   https://timeline.keylightpiano.com/music/22.06.2026 - Sinatra - ... - 2.mid
 *
 * We match recordings by their `fileName` (audio) or `midiFileName`, so the
 * job here is: pull the last path segment (decoded) and decide whether it's an
 * audio or a midi link based on its extension.
 */
object DeepLinkParser {

    enum class LinkType { AUDIO, MIDI }

    data class ParsedLink(
        val fileName: String,   // decoded last path segment, e.g. "... - 2.mp3"
        val type: LinkType
    )

    /**
     * Returns a ParsedLink if the URI looks like one of our media links,
     * or null if it's something we don't handle.
     */
    fun parse(uri: Uri): ParsedLink? {
        // Uri.lastPathSegment is automatically percent-decoded.
        val segment = uri.lastPathSegment?.trim().orEmpty()
        if (segment.isEmpty()) return null

        val lower = segment.lowercase()
        val type = when {
            lower.endsWith(".mp3") -> LinkType.AUDIO
            lower.endsWith(".mid") -> LinkType.MIDI
            else -> return null
        }
        return ParsedLink(fileName = segment, type = type)
    }
}
