package com.a2i.forwarder.store

import android.content.Context
import androidx.datastore.core.DataStore
import androidx.datastore.preferences.core.Preferences
import androidx.datastore.preferences.core.edit
import androidx.datastore.preferences.core.intPreferencesKey
import androidx.datastore.preferences.core.stringPreferencesKey
import androidx.datastore.preferences.core.stringSetPreferencesKey
import androidx.datastore.preferences.preferencesDataStore
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.launch

private val Context.rulesDataStore: DataStore<Preferences> by preferencesDataStore(name = "a2i_rules")

enum class RuleMode { BLACKLIST, WHITELIST }

class AppRulesStore(
    private val context: Context,
    scope: CoroutineScope,
) {
    private val ds get() = context.rulesDataStore

    private object K {
        val MODE = stringPreferencesKey("mode")
        val BLACK = stringSetPreferencesKey("blacklist")
        val WHITE = stringSetPreferencesKey("whitelist")
        val BL_VERSION = intPreferencesKey("bl_version")
    }

    val mode = MutableStateFlow(RuleMode.BLACKLIST)
    val blacklist = MutableStateFlow<Set<String>>(defaultBlacklist)
    val whitelist = MutableStateFlow<Set<String>>(emptySet())

    init {
        scope.launch {
            ds.data.collect { p ->
                mode.value = runCatching { RuleMode.valueOf(p[K.MODE] ?: "BLACKLIST") }.getOrDefault(RuleMode.BLACKLIST)
                // 默认黑名单版本迁移：把新增的噪音包补进老用户的黑名单（只增不删）
                val ver = p[K.BL_VERSION] ?: 1
                var black = p[K.BLACK] ?: defaultBlacklist
                if (ver < DEFAULT_BL_VERSION) {
                    black = black + blAdded
                    ds.edit { it[K.BLACK] = black; it[K.BL_VERSION] = DEFAULT_BL_VERSION }
                }
                blacklist.value = black
                whitelist.value = p[K.WHITE] ?: emptySet()
            }
        }
    }

    fun isForwardingOn(packageName: String): Boolean = when (mode.value) {
        RuleMode.BLACKLIST -> packageName !in blacklist.value
        RuleMode.WHITELIST -> packageName in whitelist.value
    }

    suspend fun setMode(m: RuleMode) {
        ds.edit { it[K.MODE] = m.name }
        mode.value = m
    }

    suspend fun setForwarding(packageName: String, on: Boolean) {
        when (mode.value) {
            RuleMode.BLACKLIST -> {
                val s = blacklist.value.toMutableSet()
                if (on) s.remove(packageName) else s.add(packageName)
                ds.edit { it[K.BLACK] = s }
                blacklist.value = s
            }
            RuleMode.WHITELIST -> {
                val s = whitelist.value.toMutableSet()
                if (on) s.add(packageName) else s.remove(packageName)
                ds.edit { it[K.WHITE] = s }
                whitelist.value = s
            }
        }
    }

    companion object {
        private const val DEFAULT_BL_VERSION = 3

        // 默认黑名单增量（累积，用于老用户版本迁移，只补不删）
        private val blAdded = setOf(
            // v2
            "com.android.soundrecorder",      // 录音机
            "com.google.android.apps.photos", // 相册
            "com.xiaomi.finddevice",          // 查找手机
            "com.miui.passwords",             // 密码管理
            // v3：通话过程中的系统状态通知，会与来电(PhoneCallMonitor)重复
            "com.android.server.telecom",     // 通话管理
            "com.xiaomi.aiasst.service",      // AI通话
        )

        val defaultBlacklist = setOf(
            // Android 系统
            "com.android.systemui",
            "com.android.settings",
            "com.android.permissioncontroller",
            // 注意：com.android.phone / com.android.incallui 不在黑名单中，电话通知需要转发
            // 输入法
            "com.google.android.inputmethod",
            "com.google.android.inputmethod.latin",
            "com.iflytek.inputmethod",
            "com.baidu.input",
            "com.sohu.inputmethod.sogou",
            // 三星剪贴板 / 键盘（经常弹出 UniversalClipboardService 等空通知）
            "com.samsung.android.honeyboard",
            "com.samsung.android.app.clipboard",
            "com.samsung.android.clipboard",
            "com.samsung.android.rubin.app",
            // Google Play Services（经常发内部状态通知）
            "com.google.android.gms",
            "com.google.android.gms.persistent",
            // a2i 自身
            "com.a2i.forwarder",
            // [v2] 纯噪音 App：转发无意义，默认屏蔽
            "com.android.soundrecorder",      // 录音机
            "com.google.android.apps.photos", // 相册
            "com.xiaomi.finddevice",          // 查找手机
            "com.miui.passwords",             // 密码管理
            // [v3] 通话状态噪音：来电由 PhoneCallMonitor 独立处理，这两个会重复
            "com.android.server.telecom",     // 通话管理
            "com.xiaomi.aiasst.service",      // AI通话
        )
    }
}
