package me.khodak.claudeusage

/**
 * Pace projection mirroring hamed-elfayome/Claude-Usage-Tracker's PaceStatus.
 *
 * Idea: if you keep your current burn rate, where do you land at reset?
 *   projected = (usedPct / 100) / elapsedFraction
 * The "where you should be right now" marker sits at elapsedFraction*100 on the bar —
 * i.e. the position that finishes at exactly 100% by reset.
 */
object PaceCalc {

    const val SESSION_WINDOW_MS = 5L * 60 * 60 * 1000          // 5 hours
    const val WEEKLY_WINDOW_MS = 7L * 24 * 60 * 60 * 1000      // 7 days

    // System-style tier colors (ARGB).
    private const val GREEN = 0xFF34C759.toInt()
    private const val TEAL = 0xFF30B0C7.toInt()
    private const val YELLOW = 0xFFFFCC00.toInt()
    private const val ORANGE = 0xFFFF9500.toInt()
    private const val RED = 0xFFFF3B30.toInt()
    private const val PURPLE = 0xFFAF52DE.toInt()

    data class Pace(
        val markerPct: Int,     // where you "should be" now (0..100)
        val projected: Float,   // projected end-of-period fraction (1.0 == exactly 100%)
        val tierColor: Int,     // ARGB color for the tier
        val label: String       // short interpretation, e.g. "sustainable pace"
    )

    /**
     * @param usedPct current utilization 0..100
     * @param resetEpoch epoch millis when this window resets (period end)
     * @param windowMs total length of the window
     * @return Pace, or null if we can't meaningfully project yet
     */
    fun compute(
        usedPct: Float,
        resetEpoch: Long,
        windowMs: Long,
        now: Long = System.currentTimeMillis()
    ): Pace? {
        if (resetEpoch <= 0L || usedPct < 0f) return null
        val start = resetEpoch - windowMs
        val elapsed = now - start
        val elapsedFraction = elapsed.toFloat() / windowMs.toFloat()
        // Match reference: need >=3% elapsed and period not complete.
        if (elapsedFraction < 0.03f || elapsedFraction >= 1.0f) return null

        val markerPct = (elapsedFraction * 100f).toInt().coerceIn(0, 100)
        if (usedPct == 0f) {
            return Pace(markerPct, 0f, GREEN, "way under budget")
        }
        val projected = (usedPct / 100f) / elapsedFraction
        val (color, label) = when {
            projected < 0.50f -> GREEN to "way under budget"
            projected < 0.75f -> TEAL to "sustainable pace"
            projected < 0.90f -> YELLOW to "starting to push it"
            projected < 1.00f -> ORANGE to "will likely hit limit"
            projected < 1.20f -> RED to "on track to exceed"
            else -> PURPLE to "burning way too fast"
        }
        return Pace(markerPct, projected, color, label)
    }
}
