package com.placeholder.sherpai2.data.local.entity

import androidx.room.ColumnInfo
import androidx.room.Entity
import androidx.room.ForeignKey
import androidx.room.Index
import androidx.room.PrimaryKey
import java.util.UUID

/**
 * FaceCacheEntity - Per-face metadata for intelligent filtering
 *
 * PURPOSE: Store face quality metrics during initial cache population
 * BENEFIT: Pre-filter to high-quality faces BEFORE clustering
 *
 * ENABLES QUERIES LIKE:
 * - "Give me all solo photos with large, clear faces"
 * - "Filter to faces that are > 15% of image"
 * - "Exclude blurry/distant/profile faces"
 *
 * POPULATED BY: PopulateFaceDetectionCacheUseCase (enhanced version)
 * USED BY: FaceClusteringService for smart photo selection
 */
@Entity(
    tableName = "face_cache",
    foreignKeys = [
        ForeignKey(
            entity = ImageEntity::class,
            parentColumns = ["imageId"],
            childColumns = ["imageId"],
            onDelete = ForeignKey.CASCADE
        )
    ],
    indices = [
        Index(value = ["imageId"]),
        Index(value = ["faceIndex"]),
        Index(value = ["faceAreaRatio"]),
        Index(value = ["qualityScore"]),
        Index(value = ["imageId", "faceIndex"], unique = true)
    ]
)
data class FaceCacheEntity(
    @PrimaryKey
    @ColumnInfo(name = "id")
    val id: String = UUID.randomUUID().toString(),

    @ColumnInfo(name = "imageId")
    val imageId: String,

    @ColumnInfo(name = "faceIndex")
    val faceIndex: Int,  // 0-based index for multiple faces in image

    // FACE METRICS (for filtering)
    @ColumnInfo(name = "boundingBox")
    val boundingBox: String,  // "left,top,right,bottom"

    @ColumnInfo(name = "faceWidth")
    val faceWidth: Int,  // pixels

    @ColumnInfo(name = "faceHeight")
    val faceHeight: Int,  // pixels

    @ColumnInfo(name = "faceAreaRatio")
    val faceAreaRatio: Float,  // face area / image area (0.0 - 1.0)

    @ColumnInfo(name = "imageWidth")
    val imageWidth: Int,  // Full image width

    @ColumnInfo(name = "imageHeight")
    val imageHeight: Int,  // Full image height

    // QUALITY INDICATORS
    @ColumnInfo(name = "qualityScore")
    val qualityScore: Float,  // 0.0-1.0 (combines size + clarity + angle)

    @ColumnInfo(name = "isLargeEnough")
    val isLargeEnough: Boolean,  // faceAreaRatio >= 0.15 AND min 200x200px

    @ColumnInfo(name = "isFrontal")
    val isFrontal: Boolean,  // Face angle roughly frontal (from ML Kit)

    @ColumnInfo(name = "hasGoodLighting")
    val hasGoodLighting: Boolean,  // Not too dark/bright (heuristic)

    // EMBEDDING (optional - for super fast clustering)
    @ColumnInfo(name = "embedding")
    val embedding: String?,  // Pre-computed 192D embedding (comma-separated)

    // METADATA
    @ColumnInfo(name = "confidence")
    val confidence: Float,  // ML Kit detection confidence

    @ColumnInfo(name = "detectedAt")
    val detectedAt: Long = System.currentTimeMillis(),

    @ColumnInfo(name = "cacheVersion")
    val cacheVersion: Int = CURRENT_CACHE_VERSION
) {
    companion object {
        const val CURRENT_CACHE_VERSION = 1

        /**
         * Convert FloatArray embedding to JSON string for storage
         */
        fun embeddingToJson(embedding: FloatArray): String {
            return embedding.joinToString(",")
        }

        /**
         * Create from ML Kit face detection result
         */
        fun create(
            imageId: String,
            faceIndex: Int,
            boundingBox: android.graphics.Rect,
            imageWidth: Int,
            imageHeight: Int,
            confidence: Float,
            isFrontal: Boolean,
            embedding: FloatArray? = null
        ): FaceCacheEntity {
            val faceWidth = boundingBox.width()
            val faceHeight = boundingBox.height()
            val faceArea = faceWidth * faceHeight
            val imageArea = imageWidth * imageHeight
            val faceAreaRatio = faceArea.toFloat() / imageArea.toFloat()

            // Calculate quality score
            val sizeScore = (faceAreaRatio * 5).coerceIn(0f, 1f)  // 20% = perfect
            val pixelScore = if (faceWidth >= 200 && faceHeight >= 200) 1f else 0.5f
            val angleScore = if (isFrontal) 1f else 0.7f
            val qualityScore = (sizeScore + pixelScore + angleScore) / 3f

            val isLargeEnough = faceAreaRatio >= 0.15f && faceWidth >= 200 && faceHeight >= 200

            return FaceCacheEntity(
                imageId = imageId,
                faceIndex = faceIndex,
                boundingBox = "${boundingBox.left},${boundingBox.top},${boundingBox.right},${boundingBox.bottom}",
                faceWidth = faceWidth,
                faceHeight = faceHeight,
                faceAreaRatio = faceAreaRatio,
                imageWidth = imageWidth,
                imageHeight = imageHeight,
                qualityScore = qualityScore,
                isLargeEnough = isLargeEnough,
                isFrontal = isFrontal,
                hasGoodLighting = true,  // TODO: Implement lighting analysis
                embedding = embedding?.joinToString(","),
                confidence = confidence
            )
        }
    }

    fun getBoundingBox(): android.graphics.Rect {
        val parts = boundingBox.split(",").map { it.toInt() }
        return android.graphics.Rect(parts[0], parts[1], parts[2], parts[3])
    }

    fun getEmbedding(): FloatArray? {
        return embedding?.split(",")?.map { it.toFloat() }?.toFloatArray()
    }
}