package com.radiola.data.repository

import com.radiola.data.remote.LrcLibApi
import com.radiola.domain.repository.LyricsRepository
import com.radiola.domain.repository.LyricsResult
import java.net.URLEncoder
import javax.inject.Inject
import javax.inject.Singleton

private const val USER_AGENT = "radiOLA Android (https://radiorecord.ru)"

@Singleton
class LyricsRepositoryImpl @Inject constructor(
    private val api: LrcLibApi
) : LyricsRepository {

    override fun providerUrl(artist: String, song: String): String {
        val query = URLEncoder.encode("$artist $song текст песни", "UTF-8")
        return "https://yandex.ru/search/?text=$query"
    }

    override suspend fun fetchLyrics(
        artist: String,
        song: String,
        durationSec: Int?
    ): LyricsResult? {
        val cleanArtist = artist.trim()
        val cleanSong = song.trim()
        if (cleanArtist.isEmpty() || cleanSong.isEmpty()) return null

        return try {
            // Сначала точный запрос
            val dto = api.get(
                userAgent = USER_AGENT,
                artistName = cleanArtist,
                trackName = cleanSong,
                durationSec = durationSec
            )
            LyricsResult(
                plain = dto.plainLyrics?.takeIf { it.isNotBlank() },
                synced = dto.syncedLyrics?.takeIf { it.isNotBlank() },
                instrumental = dto.instrumental
            )
        } catch (_: Exception) {
            // Фолбэк на поиск — берём первый результат с непустым текстом
            try {
                val results = api.search(
                    userAgent = USER_AGENT,
                    artistName = cleanArtist,
                    trackName = cleanSong
                )
                val found = results.firstOrNull { !it.plainLyrics.isNullOrBlank() }
                    ?: results.firstOrNull { it.instrumental }
                found?.let {
                    LyricsResult(
                        plain = it.plainLyrics?.takeIf { p -> p.isNotBlank() },
                        synced = it.syncedLyrics?.takeIf { s -> s.isNotBlank() },
                        instrumental = it.instrumental
                    )
                }
            } catch (_: Exception) {
                null
            }
        }
    }
}
