package com.a2i.forwarder.core

import android.Manifest
import android.content.Context
import android.content.pm.PackageManager
import android.telephony.SmsManager
import androidx.core.content.ContextCompat
import com.a2i.forwarder.A2iApp
import com.a2i.forwarder.core.NotificationProcessor.Decision
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.SupervisorJob
import kotlinx.coroutines.launch

/**
 * 短信兜底转发器：断网时把紧要通知（验证码、来电）用短信发到 iPhone。
 * 限频：每 5 分钟最多 1 条转发短信。余额 ≤5 时自动挂起。
 */
class SmsFallbackForwarder(private val context: Context) {
    private val scope = CoroutineScope(SupervisorJob() + Dispatchers.IO)
    private val RATE_LIMIT_MS = 5 * 60 * 1000L

    private val app get() = A2iApp.instance
    private val settings get() = app.settings

    /** 判断该通知是否值得走短信（断网资源宝贵）。 */
    fun isSmsWorthy(d: Decision): Boolean {
        if (d.code != null) return true                      // 验证码
        val msg = d.message ?: return false
        if (msg.group == "phone_call") return true           // 来电/未接来电
        val t = msg.title.orEmpty()
        return t.contains("来电") || t.contains("未接")
    }

    /** 尝试用短信转发。返回 true 表示已处理（无论成功失败）。 */
    fun forward(d: Decision) {
        scope.launch {
            if (!settings.smsFallbackEnabled.value) return@launch
            if (settings.smsSuspended.value) {
                log(d, "failed", "短信已挂起（余额不足）")
                return@launch
            }
            if (!isSmsWorthy(d)) return@launch
            val target = settings.smsTargetNumber.value.trim()
            if (target.isBlank()) {
                log(d, "failed", "未设置短信目标号")
                return@launch
            }
            // 限频
            val now = System.currentTimeMillis()
            val elapsed = now - settings.lastSmsSentTime.value
            if (elapsed < RATE_LIMIT_MS) {
                log(d, "filtered", "限频（${RATE_LIMIT_MS - elapsed}ms 内）")
                return@launch
            }
            // 权限
            if (ContextCompat.checkSelfPermission(context, Manifest.permission.SEND_SMS)
                != PackageManager.PERMISSION_GRANTED
            ) {
                log(d, "failed", "无 SEND_SMS 权限")
                return@launch
            }

            val body = compose(d).take(70)
            val result = runCatching {
                SmsManager.getDefault().sendTextMessage(target, null, body, null, null)
            }
            if (result.isSuccess) {
                settings.setLastSmsSentTime(now)
                log(d, "sent", "")
                // 转发后刷新余额：自动模式发查询短信，手动模式递减
                val carrier = app.carrierBalanceQuery.currentCarrier()
                if (carrier.serviceNumber != null && carrier.queryCmd != null) {
                    app.carrierBalanceQuery.refresh()
                } else {
                    app.carrierBalanceQuery.decrementManual()
                }
            } else {
                val reason = result.exceptionOrNull()?.message ?: "短信发送失败"
                log(d, "failed", reason)
            }
        }
    }

    private fun compose(d: Decision): String {
        val code = d.code
        return if (code != null) {
            "[验证码]${d.appLabel}: $code"
        } else {
            val m = d.message!!
            "${m.title.orEmpty().ifBlank { d.appLabel }}: ${m.body}".trim()
        }
    }

    private fun log(d: Decision, status: String, reason: String) {
        scope.launch {
            val now = System.currentTimeMillis()
            val title = d.code?.let { "验证码" } ?: d.message?.title ?: d.appLabel
            val content = d.code ?: d.message?.body ?: ""
            app.logStore.addLog(
                ForwardLog(now, "sms_fallback", d.appLabel, title, content, status, reason)
            )
        }
    }
}
