package com.placeholder.sherpai2.ui.presentation

import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.placeholder.sherpai2.data.local.dao.ImageDao
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.launch
import javax.inject.Inject

/**
 * MainViewModel - App-level state management for MainScreen
 *
 * Location: /ui/presentation/MainViewModel.kt (same package as MainScreen)
 *
 * Features:
 * 1. Auto-check face cache on app launch
 * 2. Prompt user if cache needs population
 * 3. Track new photos that need scanning
 */
@HiltViewModel
class MainViewModel @Inject constructor(
    private val imageDao: ImageDao
) : ViewModel() {

    private val _needsFaceCachePopulation = MutableStateFlow(false)
    val needsFaceCachePopulation: StateFlow<Boolean> = _needsFaceCachePopulation.asStateFlow()

    private val _unscannedPhotoCount = MutableStateFlow(0)
    val unscannedPhotoCount: StateFlow<Int> = _unscannedPhotoCount.asStateFlow()

    init {
        checkFaceCache()
    }

    /**
     * Check if face cache needs population
     */
    fun checkFaceCache() {
        viewModelScope.launch(Dispatchers.IO) {
            try {
                // Count photos that need face detection
                val unscanned = imageDao.getImagesNeedingFaceDetection().size

                _unscannedPhotoCount.value = unscanned
                _needsFaceCachePopulation.value = unscanned > 0

            } catch (e: Exception) {
                // Silently fail - not critical
            }
        }
    }

    /**
     * Dismiss the face cache prompt
     */
    fun dismissFaceCachePrompt() {
        _needsFaceCachePopulation.value = false
    }

    /**
     * Refresh cache status (call after populating cache)
     */
    fun refreshCacheStatus() {
        checkFaceCache()
    }
}