package com.rosetta.messenger.network

import android.content.Context
import android.hardware.Sensor
import android.hardware.SensorEvent
import android.hardware.SensorEventListener
import android.hardware.SensorManager
import android.os.PowerManager
import android.util.Log

/**
 * Controls proximity screen-off behavior during active calls.
 * Uses PROXIMITY_SCREEN_OFF_WAKE_LOCK to mimic phone-call UX.
 */
object CallProximityManager : SensorEventListener {

    private const val TAG = "CallProximityManager"
    private const val WAKE_LOCK_TAG = "Rosetta:CallProximity"

    private val lock = Any()

    private var sensorManager: SensorManager? = null
    private var proximitySensor: Sensor? = null
    private var wakeLock: PowerManager.WakeLock? = null

    private var enabled: Boolean = false
    private var listenerRegistered: Boolean = false
    private var lastNearState: Boolean? = null

    fun initialize(context: Context) {
        synchronized(lock) {
            if (sensorManager != null) return
            val app = context.applicationContext

            sensorManager = app.getSystemService(Context.SENSOR_SERVICE) as? SensorManager
            proximitySensor = sensorManager?.getDefaultSensor(Sensor.TYPE_PROXIMITY)

            val powerManager = app.getSystemService(Context.POWER_SERVICE) as? PowerManager
            val wakeSupported =
                powerManager?.isWakeLockLevelSupported(PowerManager.PROXIMITY_SCREEN_OFF_WAKE_LOCK) == true
            wakeLock =
                if (wakeSupported) {
                    powerManager
                        ?.newWakeLock(PowerManager.PROXIMITY_SCREEN_OFF_WAKE_LOCK, WAKE_LOCK_TAG)
                        ?.apply { setReferenceCounted(false) }
                } else {
                    null
                }

            Log.i(
                TAG,
                "initialize: sensor=${proximitySensor != null} wakeLockSupported=$wakeSupported"
            )
        }
    }

    fun setEnabled(context: Context, shouldEnable: Boolean) {
        initialize(context)
        synchronized(lock) {
            if (enabled == shouldEnable) return
            enabled = shouldEnable
            if (shouldEnable) {
                registerListenerLocked()
            } else {
                unregisterListenerLocked()
                releaseWakeLockLocked()
                lastNearState = null
            }
        }
    }

    fun shutdown() {
        synchronized(lock) {
            enabled = false
            unregisterListenerLocked()
            releaseWakeLockLocked()
            lastNearState = null
        }
    }

    override fun onSensorChanged(event: SensorEvent?) {
        val ev = event ?: return
        val near = isNear(ev)
        synchronized(lock) {
            if (!enabled) return
            if (lastNearState == near) return
            lastNearState = near
            if (near) {
                acquireWakeLockLocked()
            } else {
                releaseWakeLockLocked()
            }
        }
    }

    override fun onAccuracyChanged(sensor: Sensor?, accuracy: Int) = Unit

    private fun registerListenerLocked() {
        if (listenerRegistered) return
        val sm = sensorManager
        val sensor = proximitySensor
        if (sm == null || sensor == null) {
            Log.w(TAG, "register skipped: no proximity sensor")
            return
        }
        listenerRegistered = sm.registerListener(this, sensor, SensorManager.SENSOR_DELAY_NORMAL)
        Log.i(TAG, "registerListener: ok=$listenerRegistered")
    }

    private fun unregisterListenerLocked() {
        if (!listenerRegistered) return
        runCatching { sensorManager?.unregisterListener(this) }
        listenerRegistered = false
        Log.i(TAG, "unregisterListener")
    }

    private fun acquireWakeLockLocked() {
        val wl = wakeLock ?: return
        if (wl.isHeld) return
        runCatching { wl.acquire() }
            .onSuccess { Log.i(TAG, "wakeLock acquired (near)") }
            .onFailure { Log.w(TAG, "wakeLock acquire failed: ${it.message}") }
    }

    private fun releaseWakeLockLocked() {
        val wl = wakeLock ?: return
        if (!wl.isHeld) return
        runCatching { wl.release() }
            .onSuccess { Log.i(TAG, "wakeLock released (far/disabled)") }
            .onFailure { Log.w(TAG, "wakeLock release failed: ${it.message}") }
    }

    private fun isNear(event: SensorEvent): Boolean {
        val value = event.values.firstOrNull() ?: return false
        val maxRange = event.sensor.maximumRange
        // Treat as "near" if below max range and below a common 5cm threshold.
        return value < maxRange && value < 5f
    }
}

