package com.aiosman.ravenow.ui.profile

import android.util.Log
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.setValue
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.aiosman.ravenow.data.AgentRuleService
import com.aiosman.ravenow.data.AgentRuleServiceImpl
import com.aiosman.ravenow.data.AgentRuleEntity
import com.aiosman.ravenow.data.AgentRuleQuotaEntity
import com.aiosman.ravenow.data.PointService
import kotlinx.coroutines.flow.first
import kotlinx.coroutines.launch

class AgentMemoryManageViewModel(
    private val openId: String
) : ViewModel() {

    // 记忆管理相关状态
    var memoryQuota by mutableStateOf<AgentRuleQuotaEntity?>(null)
    var memoryList by mutableStateOf<List<AgentRuleEntity>>(emptyList())
    var isLoadingMemory by mutableStateOf(false)
    var memoryError by mutableStateOf<String?>(null)
    
    // Agent 规则服务
    private val agentRuleService: AgentRuleService = AgentRuleServiceImpl()
    
    // 添加记忆相关状态
    var isAddingMemory by mutableStateOf(false)
    var addMemoryError by mutableStateOf<String?>(null)
    var addMemorySuccess by mutableStateOf(false)
    var addMemoryCost by mutableStateOf<Int?>(null)
    var pointsBalance by mutableStateOf<Int?>(null)
    
    init {
        loadMemoryCost()
        loadPointsBalance()
    }
    
    /**
     * 加载积分余额
     */
    fun loadPointsBalance() {
        viewModelScope.launch {
            try {
                PointService.refreshMyPointsBalance(includeStatistics = false)
                val balance = PointService.pointsBalance.first()
                pointsBalance = balance?.balance
            } catch (e: Exception) {
                Log.e("AgentMemoryManageViewModel", "加载积分余额失败: ${e.message}", e)
            }
        }
    }
    
    /**
     * 添加 Agent 记忆
     * @param memoryText 记忆内容
     */
    fun addAgentMemory(memoryText: String) {
        viewModelScope.launch {
            try {
                isAddingMemory = true
                addMemoryError = null
                addMemorySuccess = false
                
                // 使用 Agent 规则接口创建记忆
                agentRuleService.createAgentRuleByOpenId(
                    openId = openId,
                    rule = memoryText
                )
                
                addMemorySuccess = true
                Log.d("AgentMemoryManageViewModel", "Agent 记忆添加成功")
                // 刷新记忆列表和配额
                loadMemoryQuota()
                loadMemoryList()
            } catch (e: Exception) {
                addMemoryError = e.message ?: "添加 Agent 记忆失败"
                Log.e("AgentMemoryManageViewModel", "添加 Agent 记忆失败: ${e.message}", e)
            } finally {
                isAddingMemory = false
            }
        }
    }
    
    /**
     * 获取记忆配额信息（Agent 规则配额）
     */
    fun loadMemoryQuota() {
        viewModelScope.launch {
            try {
                isLoadingMemory = true
                memoryError = null
                
                // 使用 Agent 规则接口获取配额
                memoryQuota = agentRuleService.getAgentRuleQuota(openId = openId)
            } catch (e: Exception) {
                memoryError = e.message ?: "获取配额信息失败"
                Log.e("AgentMemoryManageViewModel", "获取配额信息失败: ${e.message}", e)
            } finally {
                isLoadingMemory = false
            }
        }
    }
    
    /**
     * 获取记忆列表（Agent 规则列表）
     */
    fun loadMemoryList(page: Int = 1, pageSize: Int = 20) {
        viewModelScope.launch {
            try {
                isLoadingMemory = true
                memoryError = null
                
                // 使用 Agent 规则接口获取列表
                val result = agentRuleService.getAgentRuleList(
                    openId = openId,
                    keyword = null,
                    page = page,
                    pageSize = pageSize
                )
                memoryList = result.list
            } catch (e: Exception) {
                memoryError = e.message ?: "获取记忆列表失败"
                Log.e("AgentMemoryManageViewModel", "获取记忆列表失败: ${e.message}", e)
            } finally {
                isLoadingMemory = false
            }
        }
    }
    
    /**
     * 删除记忆（Agent 规则）
     */
    fun deleteMemory(ruleId: Int) {
        viewModelScope.launch {
            try {
                isLoadingMemory = true
                memoryError = null
                
                // 使用 Agent 规则接口删除
                agentRuleService.deleteAgentRule(ruleId)
                
                // 刷新记忆列表和配额
                loadMemoryQuota()
                loadMemoryList()
            } catch (e: Exception) {
                memoryError = e.message ?: "删除记忆失败"
                Log.e("AgentMemoryManageViewModel", "删除记忆失败: ${e.message}", e)
            } finally {
                isLoadingMemory = false
            }
        }
    }
    
    /**
     * 更新记忆（Agent 规则）
     */
    fun updateMemory(ruleId: Int, newRuleText: String) {
        viewModelScope.launch {
            try {
                isLoadingMemory = true
                memoryError = null
                
                // 使用 Agent 规则接口更新
                agentRuleService.updateAgentRule(
                    id = ruleId,
                    rule = newRuleText,
                    openId = openId
                )
                
                // 刷新记忆列表和配额
                loadMemoryQuota()
                loadMemoryList()
            } catch (e: Exception) {
                memoryError = e.message ?: "更新记忆失败"
                Log.e("AgentMemoryManageViewModel", "更新记忆失败: ${e.message}", e)
            } finally {
                isLoadingMemory = false
            }
        }
    }
    
    /**
     * 加载添加 Agent 记忆的价格
     */
    fun loadMemoryCost() {
        viewModelScope.launch {
            try {
                // 获取积分规则中的 Agent 记忆价格
                PointService.refreshPointsRules()
                val rules = PointService.pointsRules.first()
                val agentMemoryRule = rules?.sub?.get(PointService.PointsRuleKey.ADD_AGENT_MEMORY)
                addMemoryCost = when (agentMemoryRule) {
                    is PointService.RuleAmount.Fixed -> agentMemoryRule.value
                    is PointService.RuleAmount.Range -> agentMemoryRule.min
                    else -> null
                }
            } catch (e: Exception) {
                Log.e("AgentMemoryManageViewModel", "加载记忆价格失败: ${e.message}", e)
            }
        }
    }
}

