package com.placeholder.sherpai2.domain.repository

import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.net.Uri
import com.placeholder.sherpai2.data.local.dao.FaceCacheStats
import com.placeholder.sherpai2.data.local.entity.ImageEntity
import com.placeholder.sherpai2.data.local.model.ImageWithEverything
import kotlinx.coroutines.flow.Flow

/**
 * Canonical access point for images.
 *
 * ViewModels must NEVER talk directly to DAOs.
 */
interface ImageRepository {

    /**
     * Observe a fully-hydrated image graph.
     *
     * Used by detail screens.
     */
    fun observeImage(imageId: String): Flow<ImageWithEverything>

    /**
     * Ingest images discovered on device.
     *
     * This function:
     * - deduplicates
     * - assigns events automatically
     * - BLOCKS until complete (old behavior)
     */
    suspend fun ingestImages()

    /**
     * Ingest images with progress callback (NEW!)
     *
     * @param onProgress Called with (current, total) for progress updates
     */
    suspend fun ingestImagesWithProgress(onProgress: (current: Int, total: Int) -> Unit)

    /**
     * Get total image count (NEW!)
     * Fast query to check if images already loaded
     */
    suspend fun getImageCount(): Int

    fun getAllImages(): Flow<List<ImageWithEverything>>
    fun findImagesByTag(tag: String): Flow<List<ImageWithEverything>>

    fun getRecentImages(limit: Int): Flow<List<ImageWithEverything>>

    // ==========================================
    // FACE DETECTION CACHE - NEW METHODS
    // ==========================================

    /**
     * Update face detection cache for a single image
     * Called after detecting faces in an image
     */
    suspend fun updateFaceDetectionCache(
        imageId: String,
        hasFaces: Boolean,
        faceCount: Int
    )

    /**
     * Get cache statistics
     * Useful for displaying cache coverage in UI
     */
    suspend fun getFaceCacheStats(): FaceCacheStats?

    /**
     * Get images that need face detection
     * For background maintenance tasks
     */
    suspend fun getImagesNeedingFaceDetection(): List<ImageEntity>

    /**
     * Load bitmap from URI with optional BitmapFactory.Options
     * Used for face detection and other image processing
     */
    suspend fun loadBitmap(
        uri: Uri,
        options: BitmapFactory.Options? = null
    ): Bitmap?
}