package com.stand.standapp

import android.app.Application
import android.util.Log
import com.example.kingway.ptt.SendAtUtil
import com.example.kingway.ptt.pttNative
import com.stand.standapp.utils.LogManager
import timber.log.Timber
import java.io.File

class MyApplication : Application() {

    // 单例实例
    companion object {
        private lateinit var mApp: MyApplication

        @JvmStatic
        fun getAppInstance(): MyApplication {
            if (pNative == null) {
                initPTT()
            }
            return mApp
        }

        @JvmStatic
        fun initPTT() {
            if (pNative != null) return
            ensureCfgDat()
            try {
                pNative = pttNative()

                pNative?.pttNativeSetPackageName(pageName)
                pNative?.pttNativeSetAtCallback()
                pNative?.pttNativeSetPlayCallback()
                pNative?.pttNativeSetPalyStartCallback()
                pNative?.pttNativeSetPlayStopCallback()
                pNative?.pttNativeSetRecordStartCallback()
                pNative?.pttNativeSetRecordStopCallback()
                pNative?.pttNativeSetTTSCallback()

                pNative?.pttNativePocTaskStart()
                Log.i("PTT_INIT", "PTT init success")
            } catch (e: Throwable) {
                Log.e("PTT_INIT", "Failed to init PTT: ${e.message}")
            }
        }

        var pageName: String = ""
        var pNative: pttNative? = null

        /**
         * 首次安装时从 assets 复制一份有效的 cfg.dat，
         * 避免 native 读不到配置报 zpoc_init_cfg 13。
         */
        private fun ensureCfgDat() {
            try {
                val cfgFile = File("/data/data/$pageName/cfg.dat")
                if (cfgFile.exists()) return
                val app = mApp
                app.assets.open("cfg.dat").use { input ->
                    cfgFile.outputStream().use { output ->
                        input.copyTo(output)
                    }
                }
                Timber.tag("PTT_INIT").i("Copied cfg.dat from assets")
            } catch (e: Exception) {
                Timber.tag("PTT_INIT").w(e, "Failed to copy cfg.dat from assets")
            }
        }

    }

    /**
     * 获取 pttNative 实例（非空）
     */
    fun getpNative(): pttNative? {
        return pNative
    }

    override fun onCreate() {
        super.onCreate()
        mApp = this
        pageName = packageName
        
        com.stand.standapp.utils.AppKiller.setupUncaughtExceptionHandler(this)
        
        initPTT()
        // 第一步：初始化日志
        LogManager.init(this)

        // 初始化 xCrash 以捕获 Native (SO) 崩溃
        xcrash.XCrash.init(this, xcrash.XCrash.InitParameters().apply {
            setAppVersion(packageManager.getPackageInfo(packageName, 0).versionName)
            setLogDir(getExternalFilesDir("tombstones")?.absolutePath)
            setNativeDumpAllThreads(true)

            setJavaCallback { logPath, emergency ->
                LogManager.onCrashDetected(logPath, "Java-xCrash", null)
            }

            setNativeCallback { logPath, emergency ->
                LogManager.onCrashDetected(logPath, "Native-xCrash", null)
                android.util.Log.e("MyApplication", "NATIVE CRASH DETECTED at: $logPath")
            }
        })

        Timber.tag("MyApplication").i("=== Application Starting ===")
    }
}