package com.rosetta.messenger.ui.components.metaball

import android.app.ActivityManager
import android.content.Context
import android.os.Build
import android.util.Log
import java.io.RandomAccessFile
import java.util.Locale
import kotlin.math.ceil

/**
 * Device performance classification - port of Telegram's SharedConfig.measureDevicePerformanceClass()
 * Used to select the appropriate metaball rendering tier:
 * - HIGH: GPU path (Android 12+) or CPU path (older Android)
 * - AVERAGE: GPU path with reduced quality (Android 12+) or Noop (older)
 * - LOW: Noop (no metaball effect)
 */
enum class PerformanceClass {
    LOW, AVERAGE, HIGH
}

object DevicePerformanceClass {
    @Volatile
    private var cached: PerformanceClass? = null

    fun get(context: Context): PerformanceClass {
        cached?.let { return it }
        return measure(context).also {
            cached = it
            Log.d("DevicePerformance", "Performance class: $it")
        }
    }

    private fun measure(context: Context): PerformanceClass {
        val androidVersion = Build.VERSION.SDK_INT
        val cpuCount = Runtime.getRuntime().availableProcessors()
        val am = context.getSystemService(Context.ACTIVITY_SERVICE) as ActivityManager
        val memoryClass = am.memoryClass

        // Read max CPU frequency
        var totalCpuFreq = 0
        var freqResolved = 0
        for (i in 0 until cpuCount) {
            try {
                val reader = RandomAccessFile(
                    String.format(
                        Locale.ENGLISH,
                        "/sys/devices/system/cpu/cpu%d/cpufreq/cpuinfo_max_freq", i
                    ), "r"
                )
                val line = reader.readLine()
                if (line != null) {
                    totalCpuFreq += line.trim().toInt() / 1000
                    freqResolved++
                }
                reader.close()
            } catch (_: Throwable) {
            }
        }
        val maxCpuFreq = if (freqResolved == 0) -1
        else ceil(totalCpuFreq.toFloat() / freqResolved).toInt()

        // Read total RAM
        val ram: Long = try {
            val memInfo = ActivityManager.MemoryInfo()
            am.getMemoryInfo(memInfo)
            memInfo.totalMem
        } catch (_: Exception) {
            -1L
        }

        // Classification thresholds from Telegram's SharedConfig.measureDevicePerformanceClass()
        return when {
            androidVersion < 21 ||
                    cpuCount <= 2 ||
                    memoryClass <= 100 ||
                    (cpuCount <= 4 && maxCpuFreq != -1 && maxCpuFreq <= 1250) ||
                    (cpuCount <= 4 && maxCpuFreq <= 1600 && memoryClass <= 128 && androidVersion <= 21) ||
                    (cpuCount <= 4 && maxCpuFreq <= 1300 && memoryClass <= 128 && androidVersion <= 24) ||
                    (ram != -1L && ram < 2L * 1024L * 1024L * 1024L)
            -> PerformanceClass.LOW

            cpuCount < 8 ||
                    memoryClass <= 160 ||
                    (maxCpuFreq != -1 && maxCpuFreq <= 2055) ||
                    (maxCpuFreq == -1 && cpuCount == 8 && androidVersion <= 23)
            -> PerformanceClass.AVERAGE

            else -> PerformanceClass.HIGH
        }
    }
}
