package com.aiosman.ravenow.utils

import android.content.Context
import android.content.SharedPreferences
import com.google.gson.Gson
import com.google.gson.reflect.TypeToken

/**
 * 搜索历史存储（SharedPreferences + JSON）
 * - 最多保留 maxSize 条
 * - 新记录放首位，去重（忽略前后空格）
 */
class SearchHistoryStore(context: Context) {
    private val prefs: SharedPreferences =
        context.getSharedPreferences(PREF_NAME, Context.MODE_PRIVATE)
    private val gson = Gson()

    fun getHistory(): List<String> {
        val json = prefs.getString(KEY_HISTORY, "[]") ?: "[]"
        return runCatching {
            val type = object : TypeToken<List<String>>() {}.type
            gson.fromJson<List<String>>(json, type) ?: emptyList()
        }.getOrDefault(emptyList())
    }

    fun add(term: String) {
        val normalized = term.trim()
        if (normalized.isEmpty()) return
        val current = getHistory().toMutableList()
        current.removeAll { it.equals(normalized, ignoreCase = true) }
        current.add(0, normalized)
        while (current.size > MAX_SIZE) current.removeLast()
        save(current)
    }

    fun remove(term: String) {
        val normalized = term.trim()
        val current = getHistory().toMutableList()
        current.removeAll { it.equals(normalized, ignoreCase = true) }
        save(current)
    }

    fun clear() {
        save(emptyList())
    }

    private fun save(list: List<String>) {
        prefs.edit().putString(KEY_HISTORY, gson.toJson(list)).apply()
    }

    companion object {
        private const val PREF_NAME = "search_history_pref"
        private const val KEY_HISTORY = "search_history_v1"
        private const val MAX_SIZE = 10
    }
}


