package com.pangolin.pangolin_vpn

import android.app.Notification
import android.app.NotificationChannel
import android.app.NotificationManager
import android.app.PendingIntent
import android.content.Context
import android.content.Intent
import android.net.VpnService
import android.os.Build
import android.util.Log

/**
 * PangolinVpnService — VPN 服务骨架（空壳）
 *
 * 生命周期占位日志 + 前台通知；实际隧道建立由 11E 完成。
 *
 * 通信：
 *   - [MainActivity] 通过 [startVpn] / [stopVpn] 发送 Intent 启动/停止本服务
 *   - 状态回调通过 [VpnEventBus] (Application 级 LiveData) 传到 MainActivity EventSink
 *
 * TODO(11E): 在 onStartCommand 中初始化 libbox / sing-box TUN 隧道。
 */
class PangolinVpnService : VpnService() {

    companion object {
        private const val TAG = "PangolinVpnService"

        const val ACTION_START = "com.pangolin.vpn.START"
        const val ACTION_STOP  = "com.pangolin.vpn.STOP"
        const val EXTRA_CONFIG = "config_json"

        private const val NOTIFICATION_CHANNEL_ID = "pangolin_vpn_channel"
        private const val NOTIFICATION_ID = 1001

        fun startVpn(context: Context, configJson: String) {
            val intent = Intent(context, PangolinVpnService::class.java).apply {
                action = ACTION_START
                putExtra(EXTRA_CONFIG, configJson)
            }
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                context.startForegroundService(intent)
            } else {
                context.startService(intent)
            }
            Log.d(TAG, "startVpn: intent dispatched")
        }

        fun stopVpn(context: Context) {
            val intent = Intent(context, PangolinVpnService::class.java).apply {
                action = ACTION_STOP
            }
            context.startService(intent)
            Log.d(TAG, "stopVpn: intent dispatched")
        }
    }

    // ── 生命周期 ────────────────────────────────────────────────

    override fun onCreate() {
        super.onCreate()
        Log.i(TAG, "onCreate")
        createNotificationChannel()
    }

    override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
        Log.i(TAG, "onStartCommand: action=${intent?.action}")
        return when (intent?.action) {
            ACTION_START -> {
                val configJson = intent.getStringExtra(EXTRA_CONFIG) ?: "{}"
                handleStart(configJson)
                START_STICKY
            }
            ACTION_STOP -> {
                handleStop()
                START_NOT_STICKY
            }
            else -> {
                Log.w(TAG, "onStartCommand: unknown action=${intent?.action}")
                START_NOT_STICKY
            }
        }
    }

    override fun onDestroy() {
        Log.i(TAG, "onDestroy")
        handleStop()
        super.onDestroy()
    }

    override fun onRevoke() {
        Log.w(TAG, "onRevoke: VPN permission revoked by system")
        // TODO(11E): 通知 Dart 侧 status=error
        handleStop()
    }

    // ── 内部处理 ────────────────────────────────────────────────

    private fun handleStart(configJson: String) {
        Log.i(TAG, "handleStart: config=${configJson.take(80)}…")
        startForeground(NOTIFICATION_ID, buildNotification("正在连接…"))
        // TODO(11E): 解析 configJson → 构建 VPN 接口 → 启动 sing-box 内核
        // 状态变化后通过 VpnEventBus.postStatus("connecting") / ("on") 通知 MainActivity
    }

    private fun handleStop() {
        Log.i(TAG, "handleStop")
        stopForeground(true)
        stopSelf()
        // TODO(11E): 停止 sing-box 内核 → 关闭 TUN fd
    }

    // ── 前台通知 ────────────────────────────────────────────────

    private fun createNotificationChannel() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            val channel = NotificationChannel(
                NOTIFICATION_CHANNEL_ID,
                "穿山甲 VPN",
                NotificationManager.IMPORTANCE_LOW
            ).apply {
                description = "穿山甲 VPN 隧道状态"
                setShowBadge(false)
            }
            val nm = getSystemService(NotificationManager::class.java)
            nm.createNotificationChannel(channel)
        }
    }

    private fun buildNotification(contentText: String): Notification {
        val pendingFlags = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            PendingIntent.FLAG_IMMUTABLE or PendingIntent.FLAG_UPDATE_CURRENT
        } else {
            PendingIntent.FLAG_UPDATE_CURRENT
        }
        val openIntent = PendingIntent.getActivity(
            this, 0,
            Intent(this, MainActivity::class.java),
            pendingFlags
        )

        val builder = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            Notification.Builder(this, NOTIFICATION_CHANNEL_ID)
        } else {
            @Suppress("DEPRECATION")
            Notification.Builder(this)
        }

        return builder
            .setContentTitle("穿山甲")
            .setContentText(contentText)
            .setSmallIcon(android.R.drawable.ic_dialog_info)
            .setContentIntent(openIntent)
            .setOngoing(true)
            .build()
    }
}
