package com.placeholder.sherpai2.ui.trainingprep

import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.placeholder.sherpai2.data.local.dao.ImageDao
import com.placeholder.sherpai2.data.local.entity.ImageEntity
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

/**
 * TrainingPhotoSelectorViewModel - Smart photo selector for training
 *
 * KEY OPTIMIZATION:
 * - Only loads images with hasFaces=true from database
 * - Result: 10,000 photos → ~500 with faces
 * - User can quickly select 20-30 good ones
 * - Multi-select state management
 */
@HiltViewModel
class TrainingPhotoSelectorViewModel @Inject constructor(
    private val imageDao: ImageDao
) : ViewModel() {

    // Photos with faces (hasFaces=true)
    private val _photosWithFaces = MutableStateFlow<List<ImageEntity>>(emptyList())
    val photosWithFaces: StateFlow<List<ImageEntity>> = _photosWithFaces.asStateFlow()

    // Selected photos (multi-select)
    private val _selectedPhotos = MutableStateFlow<Set<ImageEntity>>(emptySet())
    val selectedPhotos: StateFlow<Set<ImageEntity>> = _selectedPhotos.asStateFlow()

    // Loading state
    private val _isLoading = MutableStateFlow(true)
    val isLoading: StateFlow<Boolean> = _isLoading.asStateFlow()

    init {
        loadPhotosWithFaces()
    }

    /**
     * Load ONLY photos with hasFaces=true
     *
     * Uses indexed query: SELECT * FROM images WHERE hasFaces = 1
     * Fast! (~10ms for 10k photos)
     *
     * SORTED: Solo photos (faceCount=1) first for best training quality
     */
    private fun loadPhotosWithFaces() {
        viewModelScope.launch {
            try {
                _isLoading.value = true

                // ✅ CRITICAL: Only get images with faces!
                val photos = imageDao.getImagesWithFaces()

                // ✅ FIX: Sort by LEAST faces first (solo photos = best training data)
                // faceCount=1 first, then faceCount=2, etc.
                val sorted = photos.sortedBy { it.faceCount ?: 999 }

                _photosWithFaces.value = sorted

            } catch (e: Exception) {
                // If face cache not populated, empty list
                _photosWithFaces.value = emptyList()
            } finally {
                _isLoading.value = false
            }
        }
    }

    /**
     * Toggle photo selection
     */
    fun toggleSelection(photo: ImageEntity) {
        val current = _selectedPhotos.value.toMutableSet()
        if (photo in current) {
            current.remove(photo)
        } else {
            current.add(photo)
        }
        _selectedPhotos.value = current
    }

    /**
     * Clear all selections
     */
    fun clearSelection() {
        _selectedPhotos.value = emptySet()
    }

    /**
     * Auto-select first N photos (quick start)
     */
    fun autoSelect(count: Int = 25) {
        val photos = _photosWithFaces.value.take(count)
        _selectedPhotos.value = photos.toSet()
    }

    /**
     * Select photos with single face only (best for training)
     */
    fun selectSingleFacePhotos(count: Int = 25) {
        val singleFacePhotos = _photosWithFaces.value
            .filter { it.faceCount == 1 }
            .take(count)
        _selectedPhotos.value = singleFacePhotos.toSet()
    }

    /**
     * Refresh data (call after face detection cache updates)
     */
    fun refresh() {
        loadPhotosWithFaces()
    }
}