package com.placeholder.sherpai2.ui.trainingprep

import android.app.Application
import android.net.Uri
import androidx.lifecycle.AndroidViewModel
import androidx.lifecycle.viewModelScope
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.launch

/**
 * ViewModel for managing training image sanity checks
 */
class TrainingSanityViewModel(application: Application) : AndroidViewModel(application) {

    private val sanityChecker = TrainingSanityChecker(application)

    private val _uiState = MutableStateFlow<TrainingSanityUiState>(TrainingSanityUiState.Idle)
    val uiState: StateFlow<TrainingSanityUiState> = _uiState.asStateFlow()

    sealed class TrainingSanityUiState {
        object Idle : TrainingSanityUiState()
        object Checking : TrainingSanityUiState()
        data class Success(
            val result: TrainingSanityChecker.SanityCheckResult
        ) : TrainingSanityUiState()
        data class Error(val message: String) : TrainingSanityUiState()
    }

    /**
     * Perform sanity checks on selected images
     */
    fun checkImages(
        imageUris: List<Uri>,
        minImagesRequired: Int = 10,
        allowMultipleFaces: Boolean = false,
        duplicateSimilarityThreshold: Double = 0.95
    ) {
        viewModelScope.launch {
            try {
                _uiState.value = TrainingSanityUiState.Checking

                val result = sanityChecker.performSanityChecks(
                    imageUris = imageUris,
                    minImagesRequired = minImagesRequired,
                    allowMultipleFaces = allowMultipleFaces,
                    duplicateSimilarityThreshold = duplicateSimilarityThreshold
                )

                _uiState.value = TrainingSanityUiState.Success(result)
            } catch (e: Exception) {
                _uiState.value = TrainingSanityUiState.Error(
                    e.message ?: "An unknown error occurred during sanity checks"
                )
            }
        }
    }

    /**
     * Reset the UI state
     */
    fun resetState() {
        _uiState.value = TrainingSanityUiState.Idle
    }

    /**
     * Get formatted error messages from validation result
     */
    fun getFormattedErrors(result: TrainingSanityChecker.SanityCheckResult): List<String> {
        return sanityChecker.formatValidationErrors(result.validationErrors)
    }

    override fun onCleared() {
        super.onCleared()
        sanityChecker.cleanup()
    }
}