package com.example.myapplication

import android.content.Context

class SuggestionStats(ctx: Context) {

    // 永远持有 applicationContext，避免泄漏/早期异常
    private val app = ctx.applicationContext

    private val prefs = app.getSharedPreferences("suggestion_stats", Context.MODE_PRIVATE)
    
    // 点击次数统计
    fun incClick(word: String?) {
        val w = word?.trim().orEmpty()

        if (w.isEmpty()) return

        val key = "cnt_$w"

        val old = prefs.getInt(key, 0)

        prefs.edit().putInt(key, old + 1).apply()
    }

    // 从应用程序的 SharedPreferences 中获取指定单词的点击次数。
    fun getCount(word: String?): Int {
        val w = word?.trim().orEmpty()

        if (w.isEmpty()) return 0

        return prefs.getInt("cnt_$w", 0)
    }

    // 按点击次数从大到小排序候选词。
    fun sortByCount(candidates: List<String?>): List<String> {
        val clean = candidates.mapNotNull { it?.trim() }.filter { it.isNotEmpty() }
        
        if (clean.isEmpty()) return emptyList()

        // 本轮候选的计数缓存（避免在 Comparator 里频繁读 SP）
        val counts = clean.asSequence().distinct().associateWith { w ->
            prefs.getInt("cnt_$w", 0)
        }

        // 稳定排序：是否有记录(1/0) -> 次数降序
        return clean.sortedWith(
            compareByDescending<String> { w -> if ((counts[w] ?: 0) > 0) 1 else 0 }
                .thenByDescending { w -> counts[w] ?: 0 }
        )
    }
}
