package com.openclaw.alfred.storage

import android.content.Context
import android.content.SharedPreferences
import com.openclaw.alfred.ui.screens.ChatMessage
import org.json.JSONArray
import org.json.JSONObject

/**
 * Persist conversation messages to SharedPreferences.
 */
object ConversationStorage {
    
    private const val PREFS_NAME = "alfred_conversation"
    private const val KEY_MESSAGES = "messages"
    private const val MAX_MESSAGES = 100  // Keep last 100 messages
    
    private fun getPrefs(context: Context): SharedPreferences {
        return context.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE)
    }
    
    /**
     * Save messages to storage.
     */
    fun saveMessages(context: Context, messages: List<ChatMessage>) {
        try {
            val jsonArray = JSONArray()
            
            // Keep only the last MAX_MESSAGES
            val messagesToSave = if (messages.size > MAX_MESSAGES) {
                messages.takeLast(MAX_MESSAGES)
            } else {
                messages
            }
            
            for (message in messagesToSave) {
                val jsonObject = JSONObject().apply {
                    put("sender", message.sender)
                    put("text", message.text)
                    put("isSystem", message.isSystem)
                }
                jsonArray.put(jsonObject)
            }
            
            getPrefs(context).edit()
                .putString(KEY_MESSAGES, jsonArray.toString())
                .apply()
                
        } catch (e: Exception) {
            android.util.Log.e("ConversationStorage", "Failed to save messages", e)
        }
    }
    
    /**
     * Load messages from storage.
     */
    fun loadMessages(context: Context): List<ChatMessage> {
        try {
            val json = getPrefs(context).getString(KEY_MESSAGES, null) ?: return emptyList()
            val jsonArray = JSONArray(json)
            val messages = mutableListOf<ChatMessage>()
            
            for (i in 0 until jsonArray.length()) {
                val jsonObject = jsonArray.getJSONObject(i)
                messages.add(
                    ChatMessage(
                        sender = jsonObject.getString("sender"),
                        text = jsonObject.getString("text"),
                        isSystem = jsonObject.getBoolean("isSystem")
                    )
                )
            }
            
            return messages
            
        } catch (e: Exception) {
            android.util.Log.e("ConversationStorage", "Failed to load messages", e)
            return emptyList()
        }
    }
    
    /**
     * Clear all stored messages.
     */
    fun clearMessages(context: Context) {
        getPrefs(context).edit()
            .remove(KEY_MESSAGES)
            .apply()
    }
}
