@file:Suppress("HardCodedStringLiteral")

package eu.gaudian.translator.utils

import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import okhttp3.OkHttpClient
import okhttp3.Request

object YouTubeApiService {


    private const val VIDEO_TITLE_URL = "http://23.88.48.47:5151/api/get_title/%s"

    private val client = OkHttpClient.Builder().build()


    suspend fun getVideoTitle(videoId: String): String = withContext(Dispatchers.IO) {
        try {
            // The URL now points to your Flask server's endpoint.
            val url = VIDEO_TITLE_URL.format(videoId)
            val request = Request.Builder().url(url).build()
            val start = System.currentTimeMillis()
            Log.d("YouTubeApiService", "Requesting video title from server: GET $url")
            val response = client.newCall(request).execute()
            val took = System.currentTimeMillis() - start
            val code = response.code
            val jsonResponse = response.body.string()
            Log.i("YouTubeApiService", "GET $url -> $code in $took ms")
            Log.d("YouTubeApiService", "Video title server response: ${jsonResponse.take(200)}")

            // The JSON from your server is simple: {"title": "The Title"}
            // This regex will parse it correctly.
            val title = "\"title\"\\s*:\\s*\"(.*?)\"".toRegex().find(jsonResponse)?.groupValues?.get(1) ?: "Unknown Title"

            if (title == "Unknown Title") {
                Log.w("YouTubeApiService", "Could not parse video title from server response for id=$videoId")
            } else {
                Log.i("YouTubeApiService", "Parsed video title: '${title.take(100)}'")
            }
            client.cache?.evictAll()
            Log.d("Cache", "OkHttp cache cleared!")
            title
        } catch (e: Exception) {
            Log.e("YouTubeApiService", "Could not fetch video title for $videoId from server", e)
            "Unknown Title"
        }
    }
}