package dev.yuzu.gca

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

class MainActivity : AppCompatActivity() {

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

        val cacheFile = File(filesDir, "gca_hot.html")
        val wv = WebView(this).apply {
            settings.javaScriptEnabled = true
            settings.domStorageEnabled = true
            settings.allowFileAccess = true
            addJavascriptInterface(Bridge(this@MainActivity), "Android")

            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 {
                val html = assets.open("frame.html").bufferedReader().readText()
                loadDataWithBaseURL("file:///android_asset/", html, "text/html", "utf-8", null)
                Log.i(TAG, "Loaded frame.html (${html.length}B)")
            }
        }
        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 too large"); return }
            File(ctx.filesDir, "gca_hot.html").writeText(html)
            Log.i(TAG, "Saved ${html.length}B")
        }

        @android.webkit.JavascriptInterface
        fun clearCache() { File(ctx.filesDir, "gca_hot.html").delete() }

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

        @android.webkit.JavascriptInterface
        fun fetchManifest(channel: String): String {
            val url = "https://git.childish-ghost.com/LukeMackin/Yuzu-GCA/raw/branch/main/ota/manifest.json"
            return try {
                val conn = URL(url).openConnection() as HttpURLConnection
                conn.connectTimeout = 10000; conn.readTimeout = 10000
                val raw = conn.inputStream.bufferedReader().readText()
                org.json.JSONObject(raw).getJSONObject(channel).toString()
            } catch (e: Exception) { """{"error":"${e.message}"}""" }
        }

        @android.webkit.JavascriptInterface
        fun fetchText(path: String): String {
            val safe = path.replace("..", "").replace("..", "").replace("\\", "/")
            val url = "https://git.childish-ghost.com/LukeMackin/Yuzu-GCA/raw/branch/main/ota/$safe"
            return try {
                URL(url).openConnection().apply { connectTimeout = 10000; readTimeout = 10000 }
                    .getInputStream().bufferedReader().readText()
            } catch (e: Exception) { "ERROR: ${e.message}" }
        }
    }

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