package com.demoscene.tv

import android.os.Bundle
import android.util.Log
import android.view.View
import android.widget.TextView
import androidx.fragment.app.FragmentActivity
import com.demoscene.tv.data.PouetCache
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import java.io.File
import java.util.Calendar

class MainActivity : FragmentActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        // Hide logo if showing filtered category
        val categoryFilter = intent.getStringExtra("CATEGORY_FILTER")
        if (categoryFilter != null) {
            findViewById<TextView>(R.id.logo_overlay)?.visibility = View.GONE
        }

        // Silent background refresh - doesn't block UI
        CoroutineScope(Dispatchers.IO).launch {
            checkAndRefreshCache()
            checkAndRefreshGfx()
        }
    }

    override fun onBackPressed() {
        finishAffinity()
    }

    private suspend fun checkAndRefreshCache() {
        val cacheFile = File(filesDir, "pouet_filtered.json")
        val shouldRefresh = when {
            !cacheFile.exists() -> {
                Log.d("DemosceneTV", "No cache - already downloaded by LoadingActivity")
                false
            }
            !PouetCache.isCached(this) -> {
                Log.d("DemosceneTV", "Cache invalid - will refresh")
                true
            }
            isThursdayOrLater(cacheFile.lastModified()) -> {
                Log.d("DemosceneTV", "Cache older than last Thursday - will refresh")
                true
            }
            else -> {
                Log.d("DemosceneTV", "Cache is fresh")
                false
            }
        }

        if (shouldRefresh) {
            Log.d("DemosceneTV", "Starting silent background cache refresh...")
            try {
                PouetCache.downloadAndCache(this) { progress ->
                    Log.d("DemosceneTV", "Background: " + progress)
                }
                Log.d("DemosceneTV", "Background refresh complete!")
            } catch (e: Exception) {
                Log.e("DemosceneTV", "Background refresh failed: " + e.message)
            }
        }
    }

    private suspend fun checkAndRefreshGfx() {
        val gfxFile = File(filesDir, "weekly_gfx.json")
        
        // Refresh GFX if older than 7 days
        val shouldRefreshGfx = !gfxFile.exists() || 
            (System.currentTimeMillis() - gfxFile.lastModified()) > (7 * 24 * 60 * 60 * 1000)
        
        if (shouldRefreshGfx) {
            Log.d("DemosceneTV", "Time to refresh weekly GFX art...")
            // TODO: Fetch random GFX from Pouet graphics section
            // For now just log - we'll implement GFX fetching next
        } else {
            Log.d("DemosceneTV", "Weekly GFX still fresh")
        }
    }

    private fun isThursdayOrLater(cacheTimestamp: Long): Boolean {
        val cal = Calendar.getInstance()
        val today = cal.get(Calendar.DAY_OF_WEEK)
        
        // Get last Thursday
        cal.set(Calendar.DAY_OF_WEEK, Calendar.THURSDAY)
        cal.set(Calendar.HOUR_OF_DAY, 0)
        cal.set(Calendar.MINUTE, 0)
        cal.set(Calendar.SECOND, 0)
        
        if (cal.timeInMillis > System.currentTimeMillis()) {
            cal.add(Calendar.WEEK_OF_YEAR, -1)
        }
        
        val lastThursday = cal.timeInMillis
        
        // Cache is old if it's from before last Thursday
        return cacheTimestamp < lastThursday
    }
}
