package com.ponzischeme89.memby.performance

import android.app.Activity
import android.os.SystemClock
import android.util.Log
import androidx.metrics.performance.JankStats

/** Debug-only frame telemetry. It does not alter rendering or app state. */
object PerformanceMonitor {
    private const val TAG = "EmbyClientPerf"
    private var stats: JankStats? = null
    private var frameCount = 0
    private var jankCount = 0
    private var totalFrameMs = 0L
    private var windowStartedAt = 0L

    fun start(activity: Activity) {
        if (!com.ponzischeme89.memby.BuildConfig.DEBUG || stats != null) return
        activity.window.decorView.post {
            if (stats != null) return@post
            windowStartedAt = SystemClock.elapsedRealtime()
            stats = JankStats.createAndTrack(activity.window) { frameData ->
                frameCount++
                totalFrameMs += frameData.frameDurationUiNanos / 1_000_000L
                if (frameData.isJank) jankCount++
                if (frameCount % 120 == 0) report("window")
            }
            Log.i(TAG, "tracking started")
        }
    }

    fun mark(name: String) {
        if (stats == null) return
        report(name)
        frameCount = 0
        jankCount = 0
        totalFrameMs = 0
        windowStartedAt = SystemClock.elapsedRealtime()
    }

    private fun report(name: String) {
        if (frameCount == 0) return
        val elapsed = SystemClock.elapsedRealtime() - windowStartedAt
        Log.i(
            TAG,
            "$name frames=$frameCount jank=$jankCount avgUiMs=${totalFrameMs / frameCount} elapsedMs=$elapsed",
        )
    }
}
