package com.demoscene.tv.data

import android.content.Context
import android.util.Log
import com.google.gson.Gson
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import java.io.File

data class WeeklyGfx(
    val prodId: String,
    val title: String,
    val group: String,
    val year: Int,
    val imageUrl: String,
    val pouetUrl: String,
    val downloadedTimestamp: Long
)

object GfxManager {
    
    suspend fun getWeeklyGfx(context: Context): WeeklyGfx? = withContext(Dispatchers.IO) {
        val cacheFile = File(context.filesDir, "weekly_gfx.json")
        
        // Check if we have cached GFX less than 7 days old
        if (cacheFile.exists()) {
            try {
                val cached = Gson().fromJson(cacheFile.readText(), WeeklyGfx::class.java)
                val age = System.currentTimeMillis() - cached.downloadedTimestamp
                if (age < (7 * 24 * 60 * 60 * 1000)) {
                    Log.d("DemosceneTV", "Using cached weekly GFX: " + cached.title)
                    return@withContext cached
                }
            } catch (e: Exception) {
                Log.e("DemosceneTV", "Error loading cached GFX: " + e.message)
            }
        }
        
        // Pick new random GFX from our demo dump
        try {
            Log.d("DemosceneTV", "Selecting new weekly GFX from database...")
            val dump = PouetCache.loadFromCache(context)
            val prods = dump?.prods ?: return@withContext null
            
            // Filter for graphics type with screenshots
            val gfxProds = prods.filter { prod ->
                val type = prod.type?.lowercase() ?: ""
                val hasScreenshot = !prod.screenshot.isNullOrEmpty()
                (type.contains("graphics") || type.contains("gfx")) && hasScreenshot
            }
            
            if (gfxProds.isEmpty()) {
                Log.d("DemosceneTV", "No GFX productions found with screenshots")
                return@withContext null
            }
            
            // Pick a random one
            val randomGfx = gfxProds.random()
            
            val groupName = extractGroupName(randomGfx.groups)
            val year = randomGfx.releaseDate?.substring(0, 4)?.toIntOrNull() ?: 0
            
            val weeklyGfx = WeeklyGfx(
                prodId = randomGfx.id ?: "0",
                title = randomGfx.name ?: "Unknown",
                group = groupName,
                year = year,
                imageUrl = randomGfx.screenshot ?: "",
                pouetUrl = "https://www.pouet.net/prod.php?which=" + (randomGfx.id ?: "0"),
                downloadedTimestamp = System.currentTimeMillis()
            )
            
            cacheFile.writeText(Gson().toJson(weeklyGfx))
            Log.d("DemosceneTV", "New weekly GFX: " + weeklyGfx.title + " by " + weeklyGfx.group)
            
            return@withContext weeklyGfx
            
        } catch (e: Exception) {
            Log.e("DemosceneTV", "Error selecting GFX: " + e.message, e)
            return@withContext null
        }
    }
    
    private fun extractGroupName(groupsElement: com.google.gson.JsonElement?): String {
        try {
            if (groupsElement == null) return "Unknown"
            if (groupsElement.isJsonArray) {
                val firstGroup = groupsElement.asJsonArray.firstOrNull()
                if (firstGroup?.isJsonObject == true) {
                    return firstGroup.asJsonObject.get("name")?.asString ?: "Unknown"
                }
            } else if (groupsElement.isJsonObject) {
                return groupsElement.asJsonObject.get("name")?.asString ?: "Unknown"
            }
        } catch (e: Exception) {}
        return "Unknown"
    }
}
