package com.divyagkquiz.app.data

import android.content.Context
import com.google.gson.Gson
import com.google.gson.reflect.TypeToken
import java.io.IOException

class QuizRepository(private val context: Context) {

    private var cachedQuestions: List<Question>? = null

    fun getQuestions(): List<Question> {
        if (cachedQuestions != null) return cachedQuestions!!
        
        val jsonString: String
        try {
            jsonString = context.assets.open("questions.json").bufferedReader().use { it.readText() }
        } catch (ioException: IOException) {
            ioException.printStackTrace()
            return emptyList()
        }
        val listType = object : TypeToken<List<Question>>() {}.type
        cachedQuestions = Gson().fromJson(jsonString, listType)
        return cachedQuestions ?: emptyList()
    }

    fun getCategoryCounts(): Map<String, Int> {
        val questions = getQuestions()
        return questions.groupBy { it.category }.mapValues { it.value.size }
    }

    fun getDailyQuestion(): Question? {
        val questions = getQuestions()
        return if (questions.isNotEmpty()) {
            questions.shuffled().firstOrNull() 
        } else {
            null
        }
    }
}
