package com.openclaw.alfred.storage

import android.content.Context
import android.content.SharedPreferences
import org.json.JSONArray
import org.json.JSONObject

/**
 * Stores notification history for in-app display.
 */
class NotificationStorage(context: Context) {
    private val prefs: SharedPreferences = context.getSharedPreferences("alfred_notifications", Context.MODE_PRIVATE)
    
    data class StoredNotification(
        val id: String,
        val type: String,
        val title: String,
        val message: String,
        val timestamp: Long,
        val read: Boolean = false
    )
    
    /**
     * Add a notification to history.
     */
    fun addNotification(type: String, title: String, message: String, timestamp: Long = System.currentTimeMillis()): String {
        val notifications = getNotifications().toMutableList()
        val id = "notif_${timestamp}_${notifications.size}"
        
        notifications.add(0, StoredNotification(
            id = id,
            type = type,
            title = title,
            message = message,
            timestamp = timestamp,
            read = false
        ))
        
        // Keep only last 50 notifications
        if (notifications.size > 50) {
            notifications.subList(50, notifications.size).clear()
        }
        
        saveNotifications(notifications)
        return id
    }
    
    /**
     * Get all notifications (newest first).
     */
    fun getNotifications(): List<StoredNotification> {
        return try {
            val json = prefs.getString("notifications", null) ?: return emptyList()
            val array = JSONArray(json)
            val result = mutableListOf<StoredNotification>()
            
            for (i in 0 until array.length()) {
                try {
                    val obj = array.getJSONObject(i)
                    result.add(StoredNotification(
                        id = obj.getString("id"),
                        type = obj.getString("type"),
                        title = obj.getString("title"),
                        message = obj.getString("message"),
                        timestamp = obj.getLong("timestamp"),
                        read = obj.optBoolean("read", false)
                    ))
                } catch (e: Exception) {
                    // Skip corrupted notification entries
                    android.util.Log.e("NotificationStorage", "Failed to parse notification at index $i: ${e.message}")
                }
            }
            
            result
        } catch (e: Exception) {
            // If JSON parsing fails completely, clear corrupted data and return empty
            android.util.Log.e("NotificationStorage", "Failed to parse notifications JSON, clearing: ${e.message}")
            prefs.edit().remove("notifications").apply()
            emptyList()
        }
    }
    
    /**
     * Mark notification as read.
     */
    fun markAsRead(id: String) {
        val notifications = getNotifications().map {
            if (it.id == id) it.copy(read = true) else it
        }
        saveNotifications(notifications)
    }
    
    /**
     * Mark all notifications as read.
     */
    fun markAllAsRead() {
        val notifications = getNotifications().map { it.copy(read = true) }
        saveNotifications(notifications)
    }
    
    /**
     * Get unread count.
     */
    fun getUnreadCount(): Int {
        return getNotifications().count { !it.read }
    }
    
    /**
     * Delete a specific notification by timestamp.
     */
    fun deleteNotification(timestamp: Long) {
        val notifications = getNotifications().filter { it.timestamp != timestamp }
        saveNotifications(notifications)
    }
    
    /**
     * Clear all notifications.
     */
    fun clearAll() {
        prefs.edit().remove("notifications").apply()
    }
    
    private fun saveNotifications(notifications: List<StoredNotification>) {
        try {
            val array = JSONArray()
            notifications.forEach { notif ->
                val obj = JSONObject().apply {
                    put("id", notif.id)
                    put("type", notif.type)
                    put("title", notif.title)
                    put("message", notif.message)
                    put("timestamp", notif.timestamp)
                    put("read", notif.read)
                }
                array.put(obj)
            }
            prefs.edit().putString("notifications", array.toString()).apply()
        } catch (e: Exception) {
            android.util.Log.e("NotificationStorage", "Failed to save notifications: ${e.message}")
        }
    }
}
