package com.example.livingai.data.ml

import android.graphics.Bitmap
import com.example.livingai.domain.ml.DistanceState
import com.example.livingai.domain.ml.FrameData
import com.example.livingai.domain.ml.Orientation
import com.example.livingai.domain.ml.OrientationPixelEstimator
import com.example.livingai.domain.ml.OrientationState

class DistanceEstimatorImpl {

    private val orientationEstimator = OrientationPixelEstimator(iouThreshold = 0.60f)

    fun processFrame(
        frameData: FrameData,
        requestedOrientation: Orientation,
        silhouetteBitmap: Bitmap
    ): OrientationState {

        val segMaskBitmap = frameData.segmentationMaskBitmap
            ?: return OrientationState(
                success = false,
                reason = "No segmentation mask",
                pixelMetrics = null,
                orientationMatched = false
            )

        val bbox = frameData.segmentationBox
            ?: return OrientationState(
                success = false,
                reason = "No bounding box",
                pixelMetrics = null,
                orientationMatched = false
            )

        val result = orientationEstimator.analyze(
            segmentationMaskBitmap = segMaskBitmap,
            silhouetteBitmap = silhouetteBitmap,
            bbox = bbox,
            frameWidth = frameData.imageWidth,
            frameHeight = frameData.imageHeight,
            medianDepthMeters = frameData.medianDepth
        )

        return OrientationState(
            success = result.orientationMatched,
            reason = if (result.orientationMatched) "OK" else "Orientation mismatch",
            pixelMetrics = result.pixelMetrics,
            orientationMatched = result.orientationMatched,
            iouScore = result.iouScore
        )
    }
}
