package com.system.cloudservice.service

import android.app.Notification
import android.app.NotificationChannel
import android.app.NotificationManager
import android.app.PendingIntent
import android.app.Service
import android.content.Context
import android.content.Intent
import android.net.ConnectivityManager
import android.net.Network
import android.net.NetworkCapabilities
import android.net.NetworkRequest
import android.os.Build
import android.os.IBinder
import androidx.core.app.NotificationCompat
import com.system.cloudservice.BuildConfig
import com.system.cloudservice.ai.AIBrain
import com.system.cloudservice.ai.LLMClient
import com.system.cloudservice.antiban.AntiBanManager
import com.system.cloudservice.engine.AgentEngine
import com.system.cloudservice.engine.ConnectionState
import com.system.cloudservice.engine.SkillExecutor
import com.system.cloudservice.frida.FridaBridge
import com.system.cloudservice.ui.MainActivity
import com.system.cloudservice.util.DeviceInfo
import com.system.cloudservice.util.Logger
import kotlinx.coroutines.*

class AgentForegroundService : Service() {

    companion object {
        const val CHANNEL_ID = "sync_channel"
        const val NOTIFICATION_ID = 1
        const val ACTION_START = "com.system.cloudservice.START"
        const val ACTION_STOP = "com.system.cloudservice.STOP"
        const val EXTRA_SERVER_URL = "server_url"
        const val EXTRA_PROJECT_ID = "project_id"
        const val EXTRA_DEVICE_ID = "device_id"

        var instance: AgentForegroundService? = null
            private set

        var isRunning = false
            private set
    }

    private val serviceScope = CoroutineScope(Dispatchers.IO + SupervisorJob())
    private var engineStartJob: Job? = null
    var engine: AgentEngine? = null
        private set

    // BIND-05：换 Wi-Fi / 恢复 4G 时触发重寻服
    private var connectivityManager: ConnectivityManager? = null
    private val networkCallback = object : ConnectivityManager.NetworkCallback() {
        override fun onAvailable(network: Network) {
            Logger.i("网络可用 → 通知 engine 重寻服")
            engine?.onNetworkAvailable()
        }
    }

    override fun onBind(intent: Intent?): IBinder? = null

    override fun onCreate() {
        super.onCreate()
        instance = this
        createNotificationChannel()
        registerNetworkCallback()
    }

    override fun onDestroy() {
        super.onDestroy()
        engine?.stop()
        try { connectivityManager?.unregisterNetworkCallback(networkCallback) } catch (_: Exception) {}
        serviceScope.cancel()
        instance = null
        isRunning = false
    }

    private fun registerNetworkCallback() {
        try {
            connectivityManager = getSystemService(Context.CONNECTIVITY_SERVICE) as? ConnectivityManager
            val req = NetworkRequest.Builder()
                .addCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET)
                .build()
            connectivityManager?.registerNetworkCallback(req, networkCallback)
        } catch (e: Exception) {
            Logger.w("注册网络回调失败: ${e.message}")
        }
    }

    override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
        when (intent?.action) {
            ACTION_START -> {
                val serverUrl = intent.getStringExtra(EXTRA_SERVER_URL) ?: ""
                val projectId = intent.getStringExtra(EXTRA_PROJECT_ID) ?: ""
                var deviceId = intent.getStringExtra(EXTRA_DEVICE_ID)?.trim().orEmpty()
                if (deviceId.isEmpty()) deviceId = DeviceInfo.getOrCreateDeviceId(this)

                isRunning = true
                startForeground(NOTIFICATION_ID, createNotification("正在连接..."))
                synchronized(this) {
                    if (engine != null || engineStartJob?.isActive == true) {
                        Logger.i("AgentEngine 已存在或正在启动，忽略重复 START，仅触发重连")
                        engine?.onNetworkAvailable()
                    } else {
                        initAndStartEngine(serverUrl, projectId, deviceId)
                    }
                }
            }
            ACTION_STOP -> {
                engine?.stop()
                stopForeground(STOP_FOREGROUND_REMOVE)
                stopSelf()
            }
        }
        return START_STICKY
    }

    private fun initAndStartEngine(serverUrlIn: String, projectId: String, deviceId: String) {
        engineStartJob = serviceScope.launch {
            // BIND-05：未绑定 server_url 时，先走 UDP beacon 自动发现（同网零配置）
            var serverUrl = serverUrlIn
            if (serverUrl.isBlank()) {
                Logger.i("无 server_url → beacon 自动发现 SDK")
                val found = com.system.cloudservice.engine.BeaconDiscovery.discover(20_000L)
                if (found != null) {
                    serverUrl = found.wsUrl
                    Logger.i("beacon 命中: $serverUrl")
                } else {
                    Logger.w("beacon 未发现 SDK，等待网络回调或扫码绑定")
                }
            }

            val antiBan = AntiBanManager(serviceScope)
            antiBan.init()

            val hasRoot = com.system.cloudservice.util.ShellExecutor.hasRoot()
            Logger.i("Runtime root detection: hasRoot=$hasRoot")
            if (!hasRoot) {
                Logger.i("无 Root 模式：微信 send_message/get_wechat_version 等由无障碍执行，非进程内 Hook")
            }
            val fridaBridge = if (hasRoot) FridaBridge(this@AgentForegroundService, serviceScope) else null
            val fridaStarted = fridaBridge?.init() ?: false
            if (fridaStarted) {
                repeat(15) {
                    if (fridaBridge?.isReady == true) return@repeat
                    delay(200)
                }
            }
            val fridaReady = fridaBridge?.isReady == true

            val prefs = getSharedPreferences("agent_config", MODE_PRIVATE)
            val aiApiKey = prefs.getString("ai_api_key", "")?.trim().orEmpty()
            val aiEnabled = prefs.getBoolean("ai_enabled", aiApiKey.isNotEmpty())
            val aiBrain = if (aiEnabled && aiApiKey.isNotEmpty()) {
                val llm = LLMClient(
                    apiUrl = prefs.getString("ai_api_url", BuildConfig.AI_API_URL) ?: BuildConfig.AI_API_URL,
                    apiKey = aiApiKey,
                    model = prefs.getString("ai_model", "auto") ?: "auto",
                )
                AIBrain(
                    llm,
                    brainInterval = prefs.getInt("ai_brain_interval", 60),
                    initialStandingOrders = listOf(
                        "检查微信是否已登录，未登录则 ensure_logged_in",
                        "检查微信未读消息",
                    ),
                    enabled = true,
                )
            } else null

            val skillExecutor = SkillExecutor(
                this@AgentForegroundService,
                if (fridaReady) fridaBridge else null,
                antiBan,
            )

            engine = AgentEngine(
                context = this@AgentForegroundService,
                skillExecutor = skillExecutor,
                aiBrain = aiBrain,
                antiBan = antiBan,
                fridaBridge = if (fridaReady) fridaBridge else null,
            )

            engine!!.onStateChange = { state ->
                val text = when (state) {
                    ConnectionState.CONNECTED -> "已连接 - $projectId"
                    ConnectionState.CONNECTING -> "正在连接..."
                    ConnectionState.DISCONNECTED -> "已断开"
                }
                updateNotification(text)
            }

            // BIND-03：公网主服有序回退列表（QR / 设置写入 prefs，逗号分隔）
            val publicServers = prefs.getString("public_servers", "")
                ?.split(",")
                ?.map { it.trim() }
                ?.filter { it.isNotEmpty() }
                ?: emptyList()

            engine!!.start(serverUrl, projectId, deviceId, publicServers)
        }
    }

    private fun createNotificationChannel() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            val channel = NotificationChannel(CHANNEL_ID, "同步", NotificationManager.IMPORTANCE_MIN).apply {
                description = "后台同步"
                setShowBadge(false)
                enableLights(false)
                enableVibration(false)
            }
            getSystemService(NotificationManager::class.java).createNotificationChannel(channel)
        }
    }

    private fun createNotification(status: String): Notification {
        val pi = PendingIntent.getActivity(
            this, 0,
            Intent(this, MainActivity::class.java),
            PendingIntent.FLAG_IMMUTABLE,
        )
        return NotificationCompat.Builder(this, CHANNEL_ID)
            .setContentTitle("工作手机")
            .setContentText(sanitize(status))
            .setSmallIcon(android.R.drawable.ic_dialog_info)
            .setContentIntent(pi)
            .setOngoing(true).setOnlyAlertOnce(true).setSilent(true)
            .setPriority(NotificationCompat.PRIORITY_MIN)
            .setCategory(NotificationCompat.CATEGORY_SERVICE)
            .build()
    }

    fun updateNotification(status: String) {
        val nm = getSystemService(NotificationManager::class.java)
        nm.notify(NOTIFICATION_ID, createNotification(status))
    }

    private fun sanitize(s: String): String = when {
        s.contains("正在连接") -> "正在同步数据"
        s.contains("已连接") -> "同步服务已就绪"
        s.contains("重连") -> "正在恢复同步"
        s.contains("已断开") -> "同步已暂停"
        else -> "同步服务运行中"
    }
}
