package com.jidan.jiaoyi.data

import android.content.Context
import org.json.JSONArray
import org.json.JSONObject
import java.util.UUID

data class AiMessage(
    val id: String,
    val role: String,
    val text: String,
    val createdAt: Long,
    val source: String? = null,
)

class AiConversationStore(context: Context) {
    private val preferences = context.getSharedPreferences("jiaoyi_ai_chat_v1", Context.MODE_PRIVATE)

    fun loadMessages(): List<AiMessage> = runCatching {
        val array = JSONArray(preferences.getString(KEY_MESSAGES, "[]"))
        buildList {
            for (index in 0 until array.length()) {
                val item = array.getJSONObject(index)
                val role = item.optString("role")
                val text = item.optString("text").trim()
                if (role in setOf("assistant", "user") && text.isNotBlank()) {
                    add(
                        AiMessage(
                            id = item.optString("id").ifBlank { UUID.randomUUID().toString() },
                            role = role,
                            text = text,
                            createdAt = item.optLong("createdAt", System.currentTimeMillis()),
                            source = item.optString("source").ifBlank { null },
                        ),
                    )
                }
            }
        }.takeLast(MAX_MESSAGES)
    }.getOrDefault(emptyList())

    fun saveMessages(messages: List<AiMessage>) {
        val array = JSONArray()
        messages.takeLast(MAX_MESSAGES).forEach { message ->
            array.put(
                JSONObject()
                    .put("id", message.id)
                    .put("role", message.role)
                    .put("text", message.text)
                    .put("createdAt", message.createdAt)
                    .put("source", message.source ?: ""),
            )
        }
        preferences.edit().putString(KEY_MESSAGES, array.toString()).apply()
    }

    fun clear() {
        preferences.edit().remove(KEY_MESSAGES).apply()
    }

    fun loadDraft(): String = preferences.getString(KEY_DRAFT, "").orEmpty().take(500)

    fun saveDraft(value: String) {
        preferences.edit().putString(KEY_DRAFT, value.take(500)).apply()
    }

    fun newSessionId(): String = "jiaoyi-app-${System.currentTimeMillis()}-${UUID.randomUUID()}"

    private companion object {
        const val KEY_MESSAGES = "messages"
        const val KEY_DRAFT = "draft"
        const val MAX_MESSAGES = 200
    }
}
