package com.chick_mood.data.database

import android.content.Context
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import com.chick_mood.data.model.MoodRecord
import com.chick_mood.data.model.Emotion
import com.chick_mood.data.model.UserConfigEntry
import java.util.Date

/**
 * 简化的数据库管理器
 *
 * 提供基础的数据库操作，用于测试和验证数据库功能
 * 包含心情记录和用户配置的基本CRUD操作
 *
 * @author Claude
 * @date 2025-10-22
 */
class SimpleDatabaseManager private constructor(private val context: Context) {

    /**
     * 数据库实例
     */
    private val database = AppDatabase.getDatabase(context)

    /**
     * 协程作用域
     */
    private val scope = CoroutineScope(Dispatchers.IO)

    companion object {
        /**
         * 单例实例
         */
        @Volatile
        private var INSTANCE: SimpleDatabaseManager? = null

        /**
         * 获取数据库管理器实例
         *
         * @param context 应用上下文
         * @return 数据库管理器实例
         */
        fun getInstance(context: Context): SimpleDatabaseManager {
            return INSTANCE ?: synchronized(this) {
                val instance = SimpleDatabaseManager(context.applicationContext)
                INSTANCE = instance
                instance
            }
        }
    }

    // ==================== 心情记录操作 ====================

    /**
     * 创建心情记录
     */
    suspend fun createMoodRecord(
        emotion: Emotion,
        intensity: Int,
        noteText: String = "",
        imagePaths: List<String> = emptyList()
    ): Long {
        return withContext(Dispatchers.IO) {
            val moodRecord = MoodRecord(
                emotion = emotion,
                moodIntensity = intensity,
                timestamp = System.currentTimeMillis(),
                textContent = noteText,
                imagePath = imagePaths.firstOrNull()
            )

            database.moodRecordDao().insertMoodRecord(moodRecord)
        }
    }

    /**
     * 获取心情记录详情
     */
    suspend fun getMoodRecord(id: Long): MoodRecord? {
        return withContext(Dispatchers.IO) {
            database.moodRecordDao().getMoodRecordById(id)
        }
    }

    /**
     * 获取最近的心情记录
     */
    suspend fun getRecentMoodRecords(limit: Int = 10): List<MoodRecord> {
        return withContext(Dispatchers.IO) {
            database.moodRecordDao().getRecentMoodRecords(limit)
        }
    }

    /**
     * 获取心情记录总数
     */
    suspend fun getMoodRecordCount(): Int {
        return withContext(Dispatchers.IO) {
            database.moodRecordDao().getMoodRecordCount()
        }
    }

    /**
     * 更新心情记录
     */
    suspend fun updateMoodRecord(moodRecord: MoodRecord): Int {
        return withContext(Dispatchers.IO) {
            database.moodRecordDao().updateMoodRecord(moodRecord)
        }
    }

    /**
     * 删除心情记录
     */
    suspend fun deleteMoodRecord(id: Long): Int {
        return withContext(Dispatchers.IO) {
            database.moodRecordDao().deleteMoodRecordById(id)
        }
    }

    // ==================== 用户配置操作 ====================

    /**
     * 获取用户昵称
     */
    suspend fun getUserNickname(): String? {
        return withContext(Dispatchers.IO) {
            database.userConfigEntryDao().getUserNickname()
        }
    }

    /**
     * 设置用户昵称
     */
    suspend fun setUserNickname(nickname: String) {
        scope.launch {
            database.userConfigEntryDao().setUserNickname(nickname)
        }
    }

    /**
     * 设置配置值
     */
    suspend fun setConfigValue(key: String, value: String) {
        scope.launch {
            database.userConfigEntryDao().setConfigValue(key, value)
        }
    }

    /**
     * 获取配置值
     */
    suspend fun getConfigValue(key: String): String? {
        return withContext(Dispatchers.IO) {
            database.userConfigEntryDao().getConfigValue(key)
        }
    }

    /**
     * 初始化默认配置
     */
    suspend fun initializeDefaultConfig() {
        withContext(Dispatchers.IO) {
            val dao = database.userConfigEntryDao()

            // 设置默认昵称
            if (dao.getUserNickname().isNullOrEmpty()) {
                dao.setUserNickname("小鸡主人")
            }

            // 设置默认版本
            if (dao.getConfigValue(UserConfigEntry.KEY_APP_VERSION).isNullOrEmpty()) {
                dao.setAppVersion("1.0.0")
            }

            // 初始化使用天数
            if (dao.getUsageDays() == null) {
                dao.initializeUsageDays()
            }

            // 初始化心情记录计数
            if (dao.getTotalMoodRecords() == null) {
                dao.setTotalMoodRecords(0)
            }

            // 设置提醒时间
            if (dao.getReminderTime(UserConfigEntry.KEY_MORNING_REMINDER).isNullOrEmpty()) {
                dao.setReminderTime(UserConfigEntry.KEY_MORNING_REMINDER, "09:00")
            }

            if (dao.getReminderTime(UserConfigEntry.KEY_EVENING_REMINDER).isNullOrEmpty()) {
                dao.setReminderTime(UserConfigEntry.KEY_EVENING_REMINDER, "21:00")
            }

            // 设置功能开关
            if (dao.getConfigValue(UserConfigEntry.KEY_NOTIFICATION_ENABLED).isNullOrEmpty()) {
                dao.setFeatureEnabled(UserConfigEntry.KEY_NOTIFICATION_ENABLED, true)
            }

            if (dao.getConfigValue(UserConfigEntry.KEY_SOUND_ENABLED).isNullOrEmpty()) {
                dao.setFeatureEnabled(UserConfigEntry.KEY_SOUND_ENABLED, true)
            }

            if (dao.getConfigValue(UserConfigEntry.KEY_VIBRATION_ENABLED).isNullOrEmpty()) {
                dao.setFeatureEnabled(UserConfigEntry.KEY_VIBRATION_ENABLED, true)
            }
        }
    }

    // ==================== 测试方法 ====================

    /**
     * 插入测试数据
     */
    suspend fun insertTestData() {
        withContext(Dispatchers.IO) {
            // 插入测试心情记录
            val testRecords = listOf(
                MoodRecord(
                    emotion = Emotion.HAPPY,
                    moodIntensity = 85,
                    timestamp = System.currentTimeMillis(),
                    textContent = "今天心情很好！",
                    imagePath = null
                ),
                MoodRecord(
                    emotion = Emotion.SAD,
                    moodIntensity = 60,
                    timestamp = System.currentTimeMillis(),
                    textContent = "有点难过",
                    imagePath = null
                ),
                MoodRecord(
                    emotion = Emotion.ANGRY,
                    moodIntensity = 90,
                    timestamp = System.currentTimeMillis(),
                    textContent = "很生气！",
                    imagePath = null
                )
            )

            testRecords.forEach { record ->
                database.moodRecordDao().insertMoodRecord(record)
            }

            // 设置测试配置
            database.userConfigEntryDao().setUserNickname("测试用户")
            database.userConfigEntryDao().setFeatureEnabled(UserConfigEntry.KEY_SOUND_ENABLED, true)
        }
    }

    /**
     * 清理测试数据
     */
    suspend fun clearTestData() {
        withContext(Dispatchers.IO) {
            database.moodRecordDao().clearAllMoodRecords()
            database.userConfigEntryDao().clearAllUserConfigs()
        }
    }

    /**
     * 关闭数据库连接
     */
    fun close() {
        AppDatabase.closeDatabase()
    }
}