package com.system.cloudservice.ui

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import androidx.fragment.app.Fragment
import com.system.cloudservice.R
import com.system.cloudservice.engine.ConnectionState
import com.system.cloudservice.service.AgentAccessibilityService
import com.system.cloudservice.service.AgentForegroundService
import com.system.cloudservice.util.DeviceInfo
import com.system.cloudservice.util.ShellExecutor
import kotlinx.coroutines.*

class StatusFragment : Fragment() {

    private val scope = CoroutineScope(Dispatchers.Main + SupervisorJob())
    private var refreshJob: Job? = null

    private lateinit var tvConnection: TextView
    private lateinit var tvRoot: TextView
    private lateinit var tvFrida: TextView
    private lateinit var tvA11y: TextView
    private lateinit var tvAiBrain: TextView
    private lateinit var tvAntiBan: TextView
    private lateinit var tvDevice: TextView

    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View {
        return inflater.inflate(R.layout.fragment_status, container, false)
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        tvConnection = view.findViewById(R.id.tvConnection)
        tvRoot = view.findViewById(R.id.tvRoot)
        tvFrida = view.findViewById(R.id.tvFrida)
        tvA11y = view.findViewById(R.id.tvA11y)
        tvAiBrain = view.findViewById(R.id.tvAiBrain)
        tvAntiBan = view.findViewById(R.id.tvAntiBan)
        tvDevice = view.findViewById(R.id.tvDevice)
        refresh()
    }

    override fun onResume() {
        super.onResume()
        refreshJob = scope.launch {
            while (isActive) {
                refresh()
                delay(5000)
            }
        }
    }

    override fun onPause() {
        super.onPause()
        refreshJob?.cancel()
    }

    override fun onDestroyView() {
        super.onDestroyView()
        scope.cancel()
    }

    private fun refresh() {
        val svc = AgentForegroundService.instance
        val engine = svc?.engine

        val connState = engine?.wsManager?.state?.value ?: ConnectionState.DISCONNECTED
        tvConnection.text = when (connState) {
            ConnectionState.CONNECTED -> "✅ WebSocket 已连接"
            ConnectionState.CONNECTING -> "🔄 正在连接..."
            ConnectionState.DISCONNECTED -> "❌ 未连接"
        }

        scope.launch(Dispatchers.IO) {
            val hasRoot = ShellExecutor.hasRoot()
            withContext(Dispatchers.Main) { tvRoot.text = if (hasRoot) "✅ Root 可用" else "⬜ 无 Root" }
        }

        val fridaReady = engine?.isFridaReady() == true
        val hookAttached = engine?.isWechatHookAttached() == true
        tvFrida.text = when {
            engine == null -> "⬜ Frida 未启用"
            hookAttached -> "✅ 微信 Hook 已注入"
            fridaReady -> "🟡 Frida 服务就绪 · 微信 Hook 未注入"
            engine.hasFridaBridge() -> "🔄 Frida 启动中…"
            else -> "⬜ Frida 未启用（无 Root 或未拉起）"
        }

        tvA11y.text = if (isAdded && AgentAccessibilityService.isEnabled(requireContext())) {
            "✅ 无障碍服务 已启用"
        } else {
            "⬜ 无障碍服务 未启用"
        }

        tvAiBrain.text = "⬜ AI Brain 状态"
        tvAntiBan.text = "✅ 防封模块 运行中"

        scope.launch(Dispatchers.IO) {
            val info = DeviceInfo.collectQuick(requireContext())
            withContext(Dispatchers.Main) {
                tvDevice.text = buildString {
                    append("电量: ${info["battery_level"]}%")
                    if (info["battery_charging"] == true) append(" ⚡充电中")
                    append("\n内存: ${info["memory_usage_pct"]}%")
                    append("  存储余: ${info["storage_free_mb"]}MB")
                    append("\n网络: ${info["network_type"]}")
                    append("  微信: ${if (info["wechat_running"] == true) "运行中" else "未运行"}")
                }
            }
        }
    }
}
