package com.system.cloudservice.engine

import android.content.Context
import com.system.cloudservice.util.Logger
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import okhttp3.OkHttpClient
import okhttp3.Request
import java.io.File

object HotUpdateManager {

    private val listeners = mutableSetOf<() -> Unit>()
    private val http = OkHttpClient()

    fun addRefreshListener(listener: () -> Unit) {
        synchronized(listeners) { listeners.add(listener) }
    }

    fun removeRefreshListener(listener: () -> Unit) {
        synchronized(listeners) { listeners.remove(listener) }
    }

    fun notifyRefresh() {
        synchronized(listeners) { listeners.toList() }.forEach {
            try { it() } catch (e: Exception) { Logger.e("HotUpdate listener error", e) }
        }
    }

    suspend fun applyUpdate(context: Context, data: Map<String, Any?>) {
        val type = data["update_type"] as? String ?: "refresh"

        when (type) {
            "hub_html" -> {
                val url = data["url"] as? String
                val content = data["content"] as? String
                if (content != null) {
                    saveHubHtml(context, content)
                } else if (url != null) {
                    downloadAndSaveHub(context, url)
                }
                notifyRefresh()
            }
            "config" -> {
                val prefs = context.getSharedPreferences("agent_config", Context.MODE_PRIVATE).edit()
                @Suppress("UNCHECKED_CAST")
                (data["config"] as? Map<String, Any?>)?.forEach { (k, v) ->
                    when (v) {
                        is String -> prefs.putString(k, v)
                        is Boolean -> prefs.putBoolean(k, v)
                        is Number -> prefs.putLong(k, v.toLong())
                    }
                }
                prefs.apply()
                notifyRefresh()
            }
            "refresh" -> {
                notifyRefresh()
            }
        }
        Logger.i("HotUpdate applied: type=$type")
    }

    private fun saveHubHtml(context: Context, content: String) {
        val file = File(context.filesDir, "hub_override.html")
        file.writeText(content)
        Logger.i("Hub HTML saved (${content.length} chars)")
    }

    private suspend fun downloadAndSaveHub(context: Context, url: String) {
        withContext(Dispatchers.IO) {
            try {
                val req = Request.Builder().url(url).build()
                val body = http.newCall(req).execute().body?.string()
                if (!body.isNullOrEmpty()) {
                    saveHubHtml(context, body)
                }
            } catch (e: Exception) {
                Logger.e("Hub download failed: $url", e)
            }
        }
    }

    fun getHubOverridePath(context: Context): File? {
        val file = File(context.filesDir, "hub_override.html")
        return if (file.exists() && file.length() > 0) file else null
    }
}
