package com.nothing.camera2magic.hook

import android.content.ContentUris
import android.provider.MediaStore
import androidx.media3.common.MediaItem
import androidx.media3.common.Player
import androidx.media3.exoplayer.ExoPlayer
import com.nothing.camera2magic.GlobalState
import com.nothing.camera2magic.utils.Dog
import android.view.Surface

object VideoPusher {
    private const val TAG = "VideoPusher"
    private var exoPlayer: ExoPlayer? = null
    private var renderer: VirtualCameraRenderer? = null

    fun start(targetSurfaces: Collection<Surface>, width: Int, height: Int, videoId: Long) {
        Dog.i(TAG, "Starting VideoPusher for videoId: $videoId on ${targetSurfaces.size} surfaces", true)
        
        val context = GlobalState.appContext
        val videoUri = ContentUris.withAppendedId(MediaStore.Video.Media.EXTERNAL_CONTENT_URI, videoId)

        // Dynamically detect video resolution
        val retriever = android.media.MediaMetadataRetriever()
        var vWidth = 0
        var vHeight = 0
        try {
            retriever.setDataSource(context, videoUri)
            vWidth = retriever.extractMetadata(android.media.MediaMetadataRetriever.METADATA_KEY_VIDEO_WIDTH)?.toInt() ?: 0
            vHeight = retriever.extractMetadata(android.media.MediaMetadataRetriever.METADATA_KEY_VIDEO_HEIGHT)?.toInt() ?: 0
            val rotation = retriever.extractMetadata(android.media.MediaMetadataRetriever.METADATA_KEY_VIDEO_ROTATION)?.toInt() ?: 0
            if (rotation == 90 || rotation == 270) {
                val temp = vWidth
                vWidth = vHeight
                vHeight = temp
            }
        } catch (e: Exception) {
            Dog.e(TAG, "Failed to extract video metadata: ${e.message}", e, true)
        } finally {
            retriever.release()
        }

        if (renderer == null) {
            renderer = VirtualCameraRenderer()
        }
        
        renderer?.setTargetSurfaces(targetSurfaces, width, height)
        if (vWidth > 0 && vHeight > 0) {
            renderer?.setVideoSize(vWidth, vHeight)
        }

        if (exoPlayer == null) {
            exoPlayer = ExoPlayer.Builder(context).build().apply {
                repeatMode = Player.REPEAT_MODE_ALL
                playWhenReady = true
            }
        }

        exoPlayer?.apply {
            setMediaItem(MediaItem.fromUri(videoUri))
            setVideoSurface(renderer?.inputSurface)
            addListener(object : Player.Listener {
                override fun onPlayerError(error: androidx.media3.common.PlaybackException) {
                    Dog.e(TAG, "CRITICAL: ExoPlayer failed to play video. Error: ${error.message}", error, true)
                }
                override fun onPlaybackStateChanged(state: Int) {
                    val stateStr = when(state) {
                        Player.STATE_IDLE -> "IDLE"
                        Player.STATE_BUFFERING -> "BUFFERING"
                        Player.STATE_READY -> "READY"
                        Player.STATE_ENDED -> "ENDED"
                        else -> "UNKNOWN"
                    }
                    Dog.i(TAG, "ExoPlayer State: $stateStr", true)
                }
            })
            prepare()
            play()
        }
    }

    fun stop() {
        Dog.i(TAG, "Stopping VideoPusher")
        exoPlayer?.stop()
        renderer?.setTargetSurfaces(emptyList(), 0, 0)
    }

    fun release() {
        exoPlayer?.release()
        exoPlayer = null
        renderer?.release()
        renderer = null
    }
}
