package com.stove.unity

import androidx.annotation.Keep
import com.stove.gamelog.domain.GameLog
import com.stove.gamelog.domain.GameLogEvent
import com.stove.gamelog.domain.GameLogResult
import com.stove.gamelog.domain.GameLogUserInfo
import com.unity3d.player.UnityPlayer
import org.json.JSONArray
import org.json.JSONObject

/**
 * Unity <-> StoveGameLog (independent module) bridge.
 *
 * From 3.0.0 the game log is provided by the standalone `com.stove.gamelog` module,
 * which has no dependency on Base/Log. All configuration values (including GDS and user
 * info) are injected from the game via [configure].
 */
@Keep
object GameLogWrapper {
    private const val objectName = "StoveSDK"
    private const val functionName = "CallMessage"
    private const val IdentifierKey = "identifier"
    private const val ValueKey = "value"
    private const val ResultKey = "result"

    /**
     * Resolver invoked by the module at every log-creation time to obtain the latest user info.
     * Implemented on the Unity (C#) side via AndroidJavaProxy.
     */
    @Keep
    interface UserInfoResolver {
        /** @return JSON string with "userId"/"characterNo"/"worldId", or null when unavailable. */
        fun resolve(): String?
    }

    @JvmStatic
    fun configure(
        serverUrl: String,
        serviceId: String,
        marketGameId: String,
        environment: String,
        batchSize: Int,
        ip: String,
        gdsJson: String,
        language: String,
        externalId: String?,
        resolver: UserInfoResolver
    ) {
        val context = UnityPlayer.currentActivity.applicationContext
        val gdsMap = parseGds(gdsJson)

        GameLog.configure(context) {
            this.serverUrl = serverUrl
            this.serviceId = serviceId
            this.marketGameId = marketGameId
            this.environment = environment
            this.batchSize = batchSize
            this.ip = ip
            this.gds = gdsMap
            this.language = language
            this.externalId = externalId?.takeIf { it.isNotEmpty() }
            // Called lazily on a module background thread; the Unity-side proxy must be thread-safe.
            this.userInfoResolver = { parseUserInfo(resolver.resolve()) }
        }
    }

    @JvmStatic
    fun add(logEventString: String, identifier: String) {
        val logEvent = GameLogEvent.from(logEventString)
        if (logEvent == null) {
            sendResult(identifier, GameLogResult.Cancel)
            return
        }
        GameLog.add(logEvent) { result ->
            sendResult(identifier, result)
        }
    }

    @JvmStatic
    fun flush() {
        GameLog.flush()
    }

    private fun parseUserInfo(json: String?): GameLogUserInfo? {
        if (json.isNullOrEmpty()) return null
        return try {
            val obj = JSONObject(json)
            GameLogUserInfo(
                userId = if (obj.has("userId") && !obj.isNull("userId")) obj.optString("userId") else null,
                characterNo = if (obj.has("characterNo") && !obj.isNull("characterNo")) obj.optLong("characterNo") else null,
                worldId = if (obj.has("worldId") && !obj.isNull("worldId")) obj.optString("worldId") else null
            )
        } catch (e: Exception) {
            null
        }
    }

    private fun parseGds(json: String): Map<String, Any> {
        return try {
            @Suppress("UNCHECKED_CAST")
            jsonToValue(JSONObject(json)) as? Map<String, Any> ?: emptyMap()
        } catch (e: Exception) {
            emptyMap()
        }
    }

    // Recursively converts org.json values to plain Kotlin Map/List so downstream JSON
    // serialization in the module behaves consistently.
    private fun jsonToValue(value: Any?): Any? {
        return when (value) {
            is JSONObject -> {
                val map = mutableMapOf<String, Any>()
                val keys = value.keys()
                while (keys.hasNext()) {
                    val key = keys.next()
                    if (!value.isNull(key)) {
                        jsonToValue(value.get(key))?.let { map[key] = it }
                    }
                }
                map
            }
            is JSONArray -> {
                val list = mutableListOf<Any>()
                for (i in 0 until value.length()) {
                    if (!value.isNull(i)) {
                        jsonToValue(value.get(i))?.let { list.add(it) }
                    }
                }
                list
            }
            JSONObject.NULL -> null
            else -> value
        }
    }

    private fun resultToJson(result: GameLogResult): JSONObject {
        return JSONObject().apply {
            when (result) {
                is GameLogResult.Success -> {
                    put("isSuccess", true)
                    put("isCancel", false)
                }
                is GameLogResult.Cancel -> {
                    put("isSuccess", false)
                    put("isCancel", true)
                }
                is GameLogResult.Failure -> {
                    put("isSuccess", false)
                    put("isCancel", false)
                    put("errorMessage", result.error)
                }
            }
        }
    }

    private fun sendResult(identifier: String, result: GameLogResult) {
        val valueJSONObject = JSONObject().apply {
            put(ResultKey, resultToJson(result))
        }
        val jsonObject = JSONObject().apply {
            put(IdentifierKey, identifier)
            put(ValueKey, valueJSONObject)
        }
        UnityPlayer.UnitySendMessage(objectName, functionName, jsonObject.toString())
    }
}
