package com.placeholder.sherpai2.ui.imagedetail.viewmodel

import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.placeholder.sherpai2.data.local.entity.TagEntity
import com.placeholder.sherpai2.domain.repository.TaggingRepository
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.flow.*
import kotlinx.coroutines.launch
import javax.inject.Inject

/**
 * ImageDetailViewModel
 *
 * Owns:
 *  - Image context
 *  - Tag write operations
 */
@HiltViewModel
@OptIn(ExperimentalCoroutinesApi::class)
class ImageDetailViewModel @Inject constructor(
    private val tagRepository: TaggingRepository
) : ViewModel() {

    private val imageUri = MutableStateFlow<String?>(null)

    val tags: StateFlow<List<TagEntity>> =
        imageUri
            .filterNotNull()
            .flatMapLatest { uri ->
                tagRepository.getTagsForImage(uri)
            }
            .stateIn(
                scope = viewModelScope,
                started = SharingStarted.WhileSubscribed(5_000),
                initialValue = emptyList()
            )

    fun loadImage(uri: String) {
        imageUri.value = uri
    }

    fun addTag(value: String) {
        val uri = imageUri.value ?: return
        viewModelScope.launch {
            tagRepository.addTagToImage(uri, value, source = "MANUAL", confidence = 1.0f)
        }
    }

    fun removeTag(tag: TagEntity) {
        val uri = imageUri.value ?: return
        viewModelScope.launch {
            tagRepository.removeTagFromImage(uri, tag.value)
        }
    }
}
