package com.flashlink.vpn

import android.app.ActivityManager
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.os.Build
import android.os.Bundle
import android.os.Handler
import android.os.Looper
import androidx.core.content.ContextCompat
import com.google.gson.Gson

/**
 * XRay VPN API - 简化版
 * 使用广播机制与 XRayCoreService 通信
 */
class XRayApi {
    private var context: Context? = null
    private var vpnServiceEvent: OnVpnServiceEvent? = null
    private var isRegistered = false

    interface OnVpnServiceEvent {
        fun onVpnStatusChange(status: Long, code: Long, message: String)
        fun onTimerUpdate(currentTime: Long, mode: Int)
        fun onBoostResult(param: String, success: Boolean, locationCode: String, nodeId: String)
    }

    // 状态广播接收器
    private val statusReceiver = object : BroadcastReceiver() {
        override fun onReceive(context: Context?, intent: Intent?) {
            intent ?: return
            when (intent.action) {
                STATUS_BROADCAST -> {
                    val status = intent.getLongExtra("status", -1L)
                    val code = intent.getLongExtra("code", 0L)
                    val message = intent.getStringExtra("message") ?: ""
                    VLog.i(TAG, "接收到VPN状态广播: status=$status, code=$code, message=$message")
                    vpnServiceEvent?.onVpnStatusChange(status, code, message)
                }
                TIMER_BROADCAST -> {
                    val currentTime = intent.getLongExtra("currentTime", 0L)
                    val mode = intent.getIntExtra("mode", 0)
                    vpnServiceEvent?.onTimerUpdate(currentTime, mode)
                }
                BOOST_RESULT_BROADCAST -> {
                    val param = intent.getStringExtra("param") ?: ""
                    val success = intent.getBooleanExtra("success", false)
                    val locationCode = intent.getStringExtra("locationCode") ?: ""
                    val nodeId = intent.getStringExtra("nodeId") ?: ""
                    VLog.i(TAG, "接收到VPN加速结果广播: nodeId=$nodeId, locationCode=$locationCode, success=$success, param=$param,")
                    vpnServiceEvent?.onBoostResult(param, success, locationCode, nodeId)
                }
            }

        }
    }

    /**
     * 初始化 - 注册广播接收器
     */
    fun init(context: Context) {
        if (isRegistered) {
            VLog.i(TAG, "已经初始化，跳过")
            return
        }
        VLog.i(TAG, "XRayApi init")
        this.context = context

        // 注册广播接收器
        ContextCompat.registerReceiver(
            context,
            statusReceiver,
            IntentFilter().apply {
                addAction(STATUS_BROADCAST)
                addAction(TIMER_BROADCAST)
                addAction(BOOST_RESULT_BROADCAST)
            },
            ContextCompat.RECEIVER_NOT_EXPORTED
        )
        isRegistered = true
        VLog.i(TAG, "广播接收器已注册")
    }

    /**
     * 反初始化 - 注销广播接收器
     */
    fun unInit() {
        if (!isRegistered) return
        VLog.i(TAG, "XRayApi uninit")

        try {
            context?.unregisterReceiver(statusReceiver)
            VLog.i(TAG, "广播接收器已注销")
        } catch (e: Exception) {
            VLog.e(TAG, "注销广播接收器失败", e)
        }

        isRegistered = false
        context = null
    }

    /**
     * 启动 VPN
     */
    fun startXray(config: XrayConfig): Boolean {
        val ctx = context ?: run {
            VLog.e(TAG, "Context 为空，无法启动")
            return false
        }

        VLog.i(TAG, "startXray - socksPort: ${config.socksPort}, sessionId: ${config.sessionId}")

        val configJson = Gson().toJson(config)
        val intent = Intent(ctx, XRayService::class.java).apply {
            action = START_ACTION
            putExtras(Bundle().apply {
                putString("config", configJson)
            })
        }

        return try {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                ctx.startForegroundService(intent)
            } else {
                ctx.startService(intent)
            }
            VLog.i(TAG, "启动服务命令已发送")
            true
        } catch (e: Exception) {
            VLog.e(TAG, "启动服务失败", e)
            false
        }
    }

    /**
     * 停止 VPN
     */
    fun stopXray() {
        val ctx = context ?: run {
            VLog.e(TAG, "Context 为空，无法停止")
            return
        }

        VLog.i(TAG, "stopXray")

        val intent = Intent(ctx, XRayService::class.java).apply {
            action = STOP_ACTION
        }

        try {
            // 发送停止命令，让 Service 内部优雅清理资源
            ctx.startService(intent)
            VLog.i(TAG, "停止命令已发送，等待服务内部清理")
        } catch (e: Exception) {
            VLog.e(TAG, "停止服务失败", e)
        }
    }

    /**
     * 设置事件监听器
     */
    fun setVpnServiceEventListener(listener: OnVpnServiceEvent?) {
        vpnServiceEvent = listener
    }

    companion object {
        private const val TAG = "XRayApi"
        private const val STOP_TIMEOUT_MS = 500L  // 停止超时时间

        // VPN 状态常量
        const val VPN_STATE_IDLE = 0L
        const val VPN_STATE_CONNECTING = 1L
        const val VPN_STATE_CONNECTED = 2L
        const val VPN_STATE_ERROR = 3L

        /**
         * 检查 VPN 服务是否正在运行
         */
        fun isServiceRunning(context: Context): Boolean {
            val activityManager =
                context.getSystemService(Context.ACTIVITY_SERVICE) as ActivityManager

            @Suppress("DEPRECATION")
            val serviceList = activityManager.getRunningServices(300)

            if (serviceList.isEmpty()) {
                return false
            }

            return serviceList.any { it.service.className == XRayService::class.java.name }
        }
    }
}
