package dev.yuzu.gca

import android.os.Bundle
import android.util.Log
import android.webkit.WebView
import android.webkit.WebViewClient
import androidx.appcompat.app.AppCompatActivity
import java.io.File
import java.net.HttpURLConnection
import java.net.URL

class MainActivity : AppCompatActivity() {

    private val cacheFile: File by lazy { File(filesDir, "gca_hot.html") }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        val wv = WebView(this).apply {
            if (0 != (applicationInfo.flags and android.content.pm.ApplicationInfo.FLAG_DEBUGGABLE)) {
                WebView.setWebContentsDebuggingEnabled(true)
            }
            settings.javaScriptEnabled = true
            settings.domStorageEnabled = true
            settings.allowFileAccess = true
            addJavascriptInterface(Bridge(this@MainActivity), "Android")
            webViewClient = object : WebViewClient() {}

            if (cacheFile.exists()) {
                val html = cacheFile.readText()
                loadDataWithBaseURL("file:///android_asset/", html, "text/html", "UTF-8", null)
                Log.i(TAG, "Loaded cached HTML (${cacheFile.length()}B)")
            } else {
                loadUrl("file:///android_asset/index.html")
                Log.i(TAG, "Loaded embedded index.html")
            }
        }
        setContentView(wv)
    }

    inner class Bridge(private val ctx: MainActivity) {
        @android.webkit.JavascriptInterface
        fun saveCache(html: String) {
            if (html.length > 500_000) {
                Log.w(TAG, "Cache rejected: too large (${html.length}B)")
                return
            }
            ctx.cacheFile.writeText(html)
            Log.i(TAG, "Hot-update HTML saved (${html.length}B)")
        }

        @android.webkit.JavascriptInterface
        fun clearCache() {
            ctx.cacheFile.delete()
            Log.i(TAG, "Cache cleared")
        }

        @android.webkit.JavascriptInterface
        fun sha256(input: String): String {
            val md = java.security.MessageDigest.getInstance("SHA-256")
            val digest = md.digest(input.toByteArray(Charsets.UTF_8))
            return digest.joinToString("") { "%02x".format(it) }
        }

        /** Fetch manifest JSON from Gitea and return channel's section */
        @android.webkit.JavascriptInterface
        fun fetchManifest(channel: String): String {
            val manifestUrl = "https://git.childish-ghost.com/LukeMackin/Yuzu-GCA/raw/branch/main/ota/manifest.json"
            Log.i(TAG, "Bridge fetching $manifestUrl → $channel")
            return try {
                val conn = URL(manifestUrl).openConnection() as HttpURLConnection
                conn.connectTimeout = 10_000; conn.readTimeout = 10_000
                conn.instanceFollowRedirects = true
                if (conn.responseCode != 200) throw Exception("HTTP ${conn.responseCode}")
                val raw = conn.inputStream.bufferedReader().readText()
                val json = org.json.JSONObject(raw)
                json.getJSONObject(channel).toString()
            } catch (e: Exception) {
                Log.e(TAG, "Bridge fetchManifest($channel) failed: ${e.message}")
                """{"error":"${e.message}"}"""
            }
        }

        /** Fetch text file from Gitea — proxy for version.txt etc */
        @android.webkit.JavascriptInterface
        fun fetchText(path: String): String {
            val url = "https://git.childish-ghost.com/LukeMackin/Yuzu-GCA/raw/branch/main/ota/$path"
            Log.i(TAG, "Bridge fetching $url")
            return try {
                val conn = URL(url).openConnection() as HttpURLConnection
                conn.connectTimeout = 10_000
                conn.readTimeout = 10_000
                conn.instanceFollowRedirects = true
                val code = conn.responseCode
                if (code != 200) throw Exception("HTTP $code")
                conn.inputStream.bufferedReader().readText()
            } catch (e: Exception) {
                Log.e(TAG, "Bridge fetchText($path) failed: ${e.message}")
                "ERROR: ${e.message}"
            }
        }
    }

    companion object { private const val TAG = "GCA-H5" }
}
