package com.pangolin.pangolin_vpn

import android.util.Log
import io.flutter.embedding.android.FlutterActivity
import io.flutter.embedding.engine.FlutterEngine
import io.flutter.plugin.common.EventChannel
import io.flutter.plugin.common.MethodChannel

/**
 * MainActivity — Flutter ↔ 原生通道注册
 *
 * 通道契约（见 lib/bridge/vpn_bridge.dart 头部注释）：
 *   MethodChannel  : pangolin/vpn
 *   EventChannel   : pangolin/vpn/status
 *   EventChannel   : pangolin/vpn/stats
 *
 * MethodChannel 路由到 PangolinVpnService（通过 Intent）。
 * EventChannel 由 VpnEventBus 驱动（Service → EventBus → EventSink → Flutter）。
 */
class MainActivity : FlutterActivity() {

    companion object {
        private const val TAG = "PangolinMainActivity"
        private const val VPN_CHANNEL    = "pangolin/vpn"
        private const val STATUS_CHANNEL = "pangolin/vpn/status"
        private const val STATS_CHANNEL  = "pangolin/vpn/stats"
    }

    // 持有 EventSink 引用，以便 VpnEventBus 回调时转发
    private var statusEventSink: EventChannel.EventSink? = null
    private var statsEventSink: EventChannel.EventSink? = null

    override fun configureFlutterEngine(flutterEngine: FlutterEngine) {
        super.configureFlutterEngine(flutterEngine)
        val messenger = flutterEngine.dartExecutor.binaryMessenger

        // ── MethodChannel ────────────────────────────────────────
        MethodChannel(messenger, VPN_CHANNEL).setMethodCallHandler { call, result ->
            Log.d(TAG, "MethodChannel: ${call.method}")
            when (call.method) {
                "start" -> {
                    val configJson = call.arguments as? String ?: "{}"
                    PangolinVpnService.startVpn(this, configJson)
                    result.success(null)
                }
                "stop" -> {
                    PangolinVpnService.stopVpn(this)
                    result.success(null)
                }
                "getStatus" -> {
                    // TODO(11E): 从 VpnService 查询真实状态
                    result.success("off")
                }
                "selectOutbound" -> {
                    val tag = call.arguments as? String ?: "auto"
                    Log.d(TAG, "selectOutbound: tag=$tag")
                    // TODO(11E): 发送 IPC 到 VpnService → sing-box outbound selector
                    result.success(null)
                }
                "getActiveOutbound" -> {
                    // TODO(11E): 从 VpnService 查询当前出口 tag
                    result.success("auto")
                }
                "setKillSwitch" -> {
                    val on = call.arguments as? Boolean ?: false
                    Log.d(TAG, "setKillSwitch: on=$on")
                    // TODO(11E): 配置 VpnService allowedApplications / blockingMode
                    result.success(null)
                }
                else -> result.notImplemented()
            }
        }

        // ── EventChannel: status ─────────────────────────────────
        EventChannel(messenger, STATUS_CHANNEL).setStreamHandler(
            object : EventChannel.StreamHandler {
                override fun onListen(arguments: Any?, events: EventChannel.EventSink) {
                    Log.d(TAG, "status channel: onListen")
                    statusEventSink = events
                    VpnEventBus.setStatusListener(object : VpnEventBus.StatusListener {
                        override fun onStatus(status: String) {
                            statusEventSink?.success(status)
                        }
                    })
                }
                override fun onCancel(arguments: Any?) {
                    Log.d(TAG, "status channel: onCancel")
                    statusEventSink = null
                    VpnEventBus.setStatusListener(null)
                }
            }
        )

        // ── EventChannel: stats ──────────────────────────────────
        EventChannel(messenger, STATS_CHANNEL).setStreamHandler(
            object : EventChannel.StreamHandler {
                override fun onListen(arguments: Any?, events: EventChannel.EventSink) {
                    Log.d(TAG, "stats channel: onListen")
                    statsEventSink = events
                    VpnEventBus.setStatsListener(object : VpnEventBus.StatsListener {
                        override fun onStats(stats: Map<String, Any>) {
                            statsEventSink?.success(stats)
                        }
                    })
                }
                override fun onCancel(arguments: Any?) {
                    Log.d(TAG, "stats channel: onCancel")
                    statsEventSink = null
                    VpnEventBus.setStatsListener(null)
                }
            }
        )
    }

    override fun onDestroy() {
        statusEventSink = null
        statsEventSink = null
        VpnEventBus.setStatusListener(null)
        VpnEventBus.setStatsListener(null)
        super.onDestroy()
    }
}
