package com.system.cloudservice.ui

import android.annotation.SuppressLint
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.webkit.*
import androidx.fragment.app.Fragment
import com.google.gson.Gson
import com.system.cloudservice.service.AgentForegroundService
import com.system.cloudservice.util.DeviceInfo
import com.system.cloudservice.util.Logger

class HubFragment : Fragment() {

    private var webView: WebView? = null

    @SuppressLint("SetJavaScriptEnabled")
    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View {
        webView = WebView(requireContext()).apply {
            settings.javaScriptEnabled = true
            settings.domStorageEnabled = true
            settings.allowFileAccess = true
            settings.allowContentAccess = true
            settings.mixedContentMode = WebSettings.MIXED_CONTENT_ALWAYS_ALLOW
            webViewClient = WebViewClient()
            webChromeClient = WebChromeClient()
            addJavascriptInterface(NativeAgentBridge(), "NativeAgent")
            loadUrl("file:///android_asset/hub.html")
        }
        return webView!!
    }

    override fun onDestroyView() {
        webView?.destroy()
        webView = null
        super.onDestroyView()
    }

    fun canGoBack(): Boolean = webView?.canGoBack() ?: false
    fun goBack() { webView?.goBack() }

    inner class NativeAgentBridge {
        private val gson = Gson()

        @JavascriptInterface
        fun getDeviceStatus(): String {
            return try {
                val status = DeviceInfo.collectQuick(requireContext())
                val engine = AgentForegroundService.instance?.engine
                val extra = mapOf(
                    "connected" to (engine?.wsManager?.isConnected ?: false),
                    "engine_running" to (AgentForegroundService.isRunning),
                )
                gson.toJson(status + extra)
            } catch (e: Exception) {
                gson.toJson(mapOf("error" to e.message))
            }
        }

        @JavascriptInterface
        fun executeCommand(actionJson: String): String {
            return try {
                @Suppress("UNCHECKED_CAST")
                val cmd = gson.fromJson(actionJson, Map::class.java) as Map<String, Any?>
                val action = cmd["action"] as? String ?: ""
                @Suppress("UNCHECKED_CAST")
                val params = cmd["params"] as? Map<String, Any?> ?: emptyMap()
                val svc = AgentForegroundService.instance
                if (svc?.engine != null) {
                    kotlinx.coroutines.runBlocking {
                        val result = svc.engine!!.let { eng ->
                            eng.sendEvent("hub_command", mapOf("action" to action, "params" to params))
                        }
                        gson.toJson(mapOf<String, Any?>("code" to 200, "message" to "submitted", "action" to action))
                    }
                } else {
                    gson.toJson(mapOf<String, Any?>("code" to 503, "message" to "Engine not running"))
                }
            } catch (e: Exception) {
                gson.toJson(mapOf<String, Any?>("code" to 500, "message" to (e.message ?: "error")))
            }
        }

        @JavascriptInterface
        fun getConfig(): String {
            val prefs = requireContext().getSharedPreferences("agent_config", 0)
            return gson.toJson(mapOf(
                "server_url" to (prefs.getString("server_url", "") ?: ""),
                "project_id" to (prefs.getString("project_id", "") ?: ""),
                "device_id" to (prefs.getString("device_id", "") ?: ""),
                "pwa_url" to (prefs.getString("pwa_url", "") ?: ""),
                "ai_enabled" to prefs.getBoolean("ai_enabled", false),
                "ai_api_url" to (prefs.getString("ai_api_url", "") ?: ""),
            ))
        }

        /** 手机端小 AI：卡若网关 /api/gateway/chat → 决策 → 本机 Skill 执行 */
        @JavascriptInterface
        fun runAiChat(message: String): String {
            return try {
                val engine = AgentForegroundService.instance?.engine
                    ?: return gson.toJson(mapOf("code" to 503, "message" to "Agent 未运行"))
                kotlinx.coroutines.runBlocking {
                    gson.toJson(engine.runAiChat(message))
                }
            } catch (e: Exception) {
                Logger.e("runAiChat failed", e)
                gson.toJson(mapOf("code" to 500, "message" to (e.message ?: "error")))
            }
        }
    }
}
