package com.a2i.forwarder.core

import android.content.Context
import android.os.Build
import android.telephony.TelephonyManager

/**
 * 运营商检测：根据 SIM 的 MCC+MNC 映射到国内运营商。
 * 提供余额查询用的服务号 + 查询指令。
 */
object CarrierDetector {

    enum class Carrier(
        val displayName: String,
        val serviceNumber: String?,   // 余额查询服务号（免费）
        val queryCmd: String?,        // 查询指令（发送到此服务号）
    ) {
        CHINA_MOBILE("中国移动", "10086", "CXDX"),
        CHINA_UNICOM("中国联通", "10010", "CXTC"),
        CHINA_TELECOM("中国电信", "10001", "108"),
        CHINA_BROADCASTING("中国广电", "10099", null), // 无统一查询指令
        UNKNOWN("未知运营商", null, null);

        companion object {
            fun fromName(name: String?): Carrier =
                entries.firstOrNull { it.name == name } ?: UNKNOWN
        }
    }

    // MCC+MNC → 运营商（中国大陆 460）
    private val mncMap = mapOf(
        // 中国移动
        "46000" to Carrier.CHINA_MOBILE, "46002" to Carrier.CHINA_MOBILE,
        "46004" to Carrier.CHINA_MOBILE, "46007" to Carrier.CHINA_MOBILE,
        // 中国联通
        "46001" to Carrier.CHINA_UNICOM, "46006" to Carrier.CHINA_UNICOM,
        "46009" to Carrier.CHINA_UNICOM,
        // 中国电信
        "46003" to Carrier.CHINA_TELECOM, "46005" to Carrier.CHINA_TELECOM,
        "46011" to Carrier.CHINA_TELECOM, "46012" to Carrier.CHINA_TELECOM,
        // 中国广电
        "46015" to Carrier.CHINA_BROADCASTING, "46018" to Carrier.CHINA_BROADCASTING,
    )

    fun detect(context: Context): Carrier {
        return runCatching {
            val tm = context.getSystemService(Context.TELEPHONY_SERVICE) as? TelephonyManager
                ?: return Carrier.UNKNOWN
            val simOperator = tm.simOperator   // 形如 "46000"
            if (simOperator.isNullOrBlank() || simOperator.length < 5) return Carrier.UNKNOWN
            mncMap[simOperator] ?: Carrier.UNKNOWN
        }.getOrDefault(Carrier.UNKNOWN)
    }
}
