package com.example.firefly_go_android

import android.app.Activity
import android.content.Context
import android.util.Log
import libandroid.Libandroid
import java.io.File
import java.io.FileOutputStream

object FireflyModMenu {

    @Volatile
    private var isServerStarted = false

    @JvmStatic
    fun init(activity: Activity) {
        val appDataPath = File(activity.getExternalFilesDir(null), "FireflyGo").absolutePath
        val dataDir = File("$appDataPath/data")
        if (!dataDir.exists()) dataDir.mkdirs()

        val sharedPrefs = activity.getSharedPreferences("FireflyModPrefs", Context.MODE_PRIVATE)
        val modPackageName = "com.kain344.firefly_go_android"
        
        val currentUpdateTime = try {
            val packageInfo = activity.packageManager.getPackageInfo(modPackageName, 0)
            packageInfo.lastUpdateTime
        } catch (e: Exception) {
            0L
        }
        
        val lastUpdateTime = sharedPrefs.getLong("last_update_time", 0L)
        val shouldOverride = currentUpdateTime != 0L && currentUpdateTime != lastUpdateTime

        if (!isServerStarted) {
            Log.d("FireflyMod", "Start Server")
            isServerStarted = true
            Thread {
                try {
                    // Lấy context của module để truy cập assets đúng cách trong môi trường Xposed
                    val modContext = try {
                        activity.createPackageContext(modPackageName, Context.CONTEXT_IGNORE_SECURITY)
                    } catch (e: Exception) {
                        Log.e("FireflyMod", "Không thể tạo mod context: ${e.message}")
                        activity
                    }

                    val isCopyDone = copyRawFiles(modContext, dataDir, shouldOverride)
                    if (isCopyDone) {
                        if (shouldOverride) {
                            sharedPrefs.edit().putLong("last_update_time", currentUpdateTime).apply()
                        }
                        Libandroid.setPathDataLocal(appDataPath)
                        Libandroid.setServerRunning(true)
                    } else {
                        isServerStarted = false
                    }
                } catch (e: Exception) {
                    Log.e("FireflyMod", "Error starting server: ${e.message}", e)
                    isServerStarted = false
                }
            }.start()
        }
    }

    private fun copyRawFiles(context: Context, targetDir: File, override: Boolean = false): Boolean {
        val files = listOf(
            "data-in-game.json" to "data-in-game.json",
            "freesr-data.json" to "freesr-data.json",
            "version.json" to "version.json"
        )
        return try {
            for ((assetFile, outName) in files) {
                val outFile = File(targetDir, outName)
                if (outFile.exists() && !override) continue

                context.assets.open(assetFile).use { input ->
                    FileOutputStream(outFile).use { output ->
                        input.copyTo(output)
                        output.fd.sync()
                    }
                }
                Log.d("FireflyMod", "Copied $assetFile to ${outFile.absolutePath} (override=$override)")
            }
            true
        } catch (e: Exception) {
            Log.e("FireflyMod", "Error copying file: ${e.message}", e)
            false
        }
    }
}