package com.placeholder.sherpai2.ui.trainingprep

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.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.launch
import javax.inject.Inject

/**
 * ImageSelectorViewModel
 *
 * Provides face-tagged image URIs for smart filtering
 * during training photo selection.
 *
 * PRIORITIZATION: Solo photos first (faceCount=1) for clearer training data
 */
@HiltViewModel
class ImageSelectorViewModel @Inject constructor(
    private val imageDao: ImageDao
) : ViewModel() {

    private val _faceTaggedImageUris = MutableStateFlow<List<String>>(emptyList())
    val faceTaggedImageUris: StateFlow<List<String>> = _faceTaggedImageUris.asStateFlow()

    init {
        loadFaceTaggedImages()
    }

    private fun loadFaceTaggedImages() {
        viewModelScope.launch {
            try {
                // Get all images with faces
                val imagesWithFaces = imageDao.getImagesWithFaces()

                // CRITICAL FIX: Sort by faceCount ASCENDING (solo photos first!)
                // Previously: Sorted by faceCount DESC (group photos first - WRONG!)
                // Now: Solo photos appear first, making training selection easier
                val sortedImages = imagesWithFaces.sortedBy { it.faceCount }

                _faceTaggedImageUris.value = sortedImages.map { it.imageUri }
            } catch (e: Exception) {
                // If cache not available, just use empty list (filter disabled)
                _faceTaggedImageUris.value = emptyList()
            }
        }
    }
}