package com.aiosman.ravenow

import android.app.Application
import android.content.Context
import android.content.res.Configuration
import android.util.Log
import com.google.firebase.FirebaseApp
import com.google.firebase.perf.FirebasePerformance

/**
 * 自定义Application类，用于处理多进程中的Firebase初始化
 */
class RaveNowApplication : Application() {
    
    override fun attachBaseContext(base: Context) {
        // 禁用字体缩放，固定字体大小为系统默认大小
        val configuration = Configuration(base.resources.configuration)
        configuration.fontScale = 1.0f
        val context = base.createConfigurationContext(configuration)
        super.attachBaseContext(context)
    }
    
    override fun onCreate() {
        super.onCreate()
        
        // 获取当前进程名
        val processName = getCurrentProcessName()
        Log.d("RaveNowApplication", "当前进程: $processName")
        
        // 在所有进程中初始化Firebase
        try {
            if (FirebaseApp.getApps(this).isEmpty()) {
                FirebaseApp.initializeApp(this)
                Log.d("RaveNowApplication", "Firebase已在进程 $processName 中初始化")
                
                // 如果是pushcore进程，禁用Firebase Performance监控
                if (processName.contains(":pushcore")) {
                    try {
                        FirebasePerformance.getInstance().isPerformanceCollectionEnabled = false
                        Log.d("RaveNowApplication", "已在pushcore进程中禁用Firebase Performance监控")
                    } catch (e: Exception) {
                        Log.w("RaveNowApplication", "禁用Firebase Performance监控失败", e)
                    }
                }
            } else {
                Log.d("RaveNowApplication", "Firebase已在进程 $processName 中存在")
            }
        } catch (e: Exception) {
            Log.e("RaveNowApplication", "Firebase初始化失败在进程 $processName", e)
        }
    }
    
    /**
     * 获取当前进程名
     */
    private fun getCurrentProcessName(): String {
        return try {
            val pid = android.os.Process.myPid()
            val activityManager = getSystemService(Context.ACTIVITY_SERVICE) as android.app.ActivityManager
            val processes = activityManager.runningAppProcesses
            processes?.find { it.pid == pid }?.processName ?: "unknown"
        } catch (e: Exception) {
            "unknown"
        }
    }
}
