package com.example.app

import android.os.Bundle
import android.webkit.WebResourceRequest
import android.webkit.WebResourceResponse
import android.webkit.WebView
import android.webkit.WebViewClient
import java.io.File
import androidx.appcompat.app.AppCompatActivity
import androidx.webkit.WebViewAssetLoader

class MainActivity : AppCompatActivity() {

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

        val webView = WebView(this)

        // Enable remote debugging for WebView so we can inspect JS console via chrome://inspect
        WebView.setWebContentsDebuggingEnabled(true)

        webView.settings.javaScriptEnabled = true
        webView.settings.domStorageEnabled = true

        val updater = WebAppUpdater(this)

        // prefer to serve files from internal storage (filesDir/webapp), fallback to packaged assets
        val internalPath = updater.getLocalWebAppPath()

        val assetLoader = WebViewAssetLoader.Builder()
            .addPathHandler("/assets/", WebViewAssetLoader.AssetsPathHandler(this))
            .build()

        webView.webViewClient = object : WebViewClient() {
            override fun shouldInterceptRequest(view: WebView?, request: WebResourceRequest?): WebResourceResponse? {
                if (request == null) return null

                // If we have a local webapp in filesDir/webapp, serve files directly from there
                val localBase = updater.getLocalWebAppPath()
                if (localBase != null) {
                    val uri = request.url
                    val path = uri.path ?: ""
                    // expecting requests like /localweb/... mapped to filesDir/webapp/...
                    if (path.startsWith("/localweb/")) {
                        val rel = path.removePrefix("/localweb/")
                        val f = File(localBase, rel)
                        if (f.exists() && f.isFile) {
                            val mime = when {
                                f.name.endsWith(".html") -> "text/html"
                                f.name.endsWith(".js") -> "application/javascript"
                                f.name.endsWith(".css") -> "text/css"
                                f.name.endsWith(".png") -> "image/png"
                                f.name.endsWith(".jpg") || f.name.endsWith(".jpeg") -> "image/jpeg"
                                else -> "application/octet-stream"
                            }
                            return WebResourceResponse(mime, "utf-8", f.inputStream())
                        }
                    }
                }

                // fallback to packaged assets via assetLoader
                return assetLoader.shouldInterceptRequest(request.url)
            }
        }

        // Start update in background; when finished, reload WebView to pick up local files
        updater.checkAndUpdate {
            runOnUiThread {
                val local = updater.getLocalWebAppPath()
                if (local != null) {
                    // if we have a local copy, load it via mapped origin
                    webView.loadUrl("https://appassets.androidplatform.net/localweb/index.html")
                } else {
                    webView.loadUrl("https://appassets.androidplatform.net/assets/index.html")
                }
            }
        }

        // show WebView immediately (it will navigate when updater completes)
        setContentView(webView)
    }
}
