package com.divya.hardinfo.data

import android.content.Context
import com.divya.hardinfo.database.FavoriteDao
import com.divya.hardinfo.database.FavoriteItem
import com.divya.hardinfo.model.Category
import com.divya.hardinfo.model.HardwareItem
import com.google.gson.Gson
import com.google.gson.reflect.TypeToken
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import java.io.IOException

class HardwareRepository(private val context: Context, private val favoriteDao: FavoriteDao, private val searchHistoryDao: com.divya.hardinfo.database.SearchHistoryDao) {

    private var allCategories: List<Category> = emptyList()

    suspend fun getCategories(): List<Category> {
        if (allCategories.isEmpty()) {
            allCategories = loadCategoriesFromAssets()
        }
        val favorites = favoriteDao.getAllFavorites().map { it.id }.toSet()
        updateFavoritesStatus(favorites)
        return allCategories
    }

    suspend fun getAllItems(): List<HardwareItem> {
        if (allCategories.isEmpty()) {
            getCategories()
        }
        return allCategories.flatMap { it.items }
    }

    suspend fun getItemById(id: String): HardwareItem? {
        return getAllItems().find { it.id == id }
    }

    suspend fun toggleFavorite(item: HardwareItem) {
        if (item.isFavorite) {
            favoriteDao.removeFavorite(item.id)
            item.isFavorite = false
        } else {
            favoriteDao.insertFavorite(FavoriteItem(item.id))
            item.isFavorite = true
        }
    }

    suspend fun getFavoriteItems(): List<HardwareItem> {
        val favoriteIds = favoriteDao.getAllFavorites().map { it.id }.toSet()
        val allItems = getAllItems()
        allItems.forEach { it.isFavorite = favoriteIds.contains(it.id) }
        return allItems.filter { it.isFavorite }

    }
    
    suspend fun searchItems(query: String): List<HardwareItem> {
        val allItems = getAllItems()
        if (query.isBlank()) return emptyList()
        return allItems.filter {
            it.name.contains(query, ignoreCase = true) ||
            it.description.contains(query, ignoreCase = true) ||
            it.category.contains(query, ignoreCase = true)
        }
    }

    private suspend fun loadCategoriesFromAssets(): List<Category> = withContext(Dispatchers.IO) {
        try {
            val jsonString = context.assets.open("hardware_data.json").bufferedReader().use { it.readText() }
            val type = object : TypeToken<List<Category>>() {}.type
            Gson().fromJson(jsonString, type)
        } catch (ioException: IOException) {
            ioException.printStackTrace()
            emptyList()
        }
    }

    private fun updateFavoritesStatus(favoriteIds: Set<String>) {
        allCategories.forEach { category ->
            category.items.forEach { item ->
                item.isFavorite = favoriteIds.contains(item.id)
            }
        }
    }

    fun getSearchHistory(): androidx.lifecycle.LiveData<List<com.divya.hardinfo.database.SearchHistoryItem>> {
        return searchHistoryDao.getRecentHistory()
    }

    suspend fun addSearchHistory(query: String) {
        searchHistoryDao.insert(com.divya.hardinfo.database.SearchHistoryItem(query))
    }

    suspend fun clearSearchHistory() {
        searchHistoryDao.clearHistory()
    }
}
