package com.durian.tssparty

import android.app.Application
import android.util.Log
import dagger.hilt.android.HiltAndroidApp
import java.io.File
import java.io.PrintWriter
import java.io.StringWriter
import java.text.SimpleDateFormat
import java.util.Date
import java.util.Locale

@HiltAndroidApp
class TssPartyApplication : Application() {

    companion object {
        private const val TAG = "TssPartyApplication"
    }

    private var defaultExceptionHandler: Thread.UncaughtExceptionHandler? = null

    override fun onCreate() {
        super.onCreate()
        Log.d(TAG, "Application onCreate")

        // Set up global exception handler
        setupCrashHandler()
    }

    private fun setupCrashHandler() {
        defaultExceptionHandler = Thread.getDefaultUncaughtExceptionHandler()

        Thread.setDefaultUncaughtExceptionHandler { thread, throwable ->
            Log.e(TAG, "=== UNCAUGHT EXCEPTION ===")
            Log.e(TAG, "Thread: ${thread.name}")
            Log.e(TAG, "Exception: ${throwable.javaClass.simpleName}")
            Log.e(TAG, "Message: ${throwable.message}")

            // Get full stack trace
            val sw = StringWriter()
            throwable.printStackTrace(PrintWriter(sw))
            val stackTrace = sw.toString()
            Log.e(TAG, "Stack trace:\n$stackTrace")

            // Try to save crash log to file
            try {
                saveCrashLog(thread, throwable, stackTrace)
            } catch (e: Exception) {
                Log.e(TAG, "Failed to save crash log: ${e.message}")
            }

            // Call the default handler
            defaultExceptionHandler?.uncaughtException(thread, throwable)
        }

        Log.d(TAG, "Crash handler installed")
    }

    private fun saveCrashLog(thread: Thread, throwable: Throwable, stackTrace: String) {
        val crashDir = File(filesDir, "crash_logs")
        if (!crashDir.exists()) {
            crashDir.mkdirs()
        }

        val dateFormat = SimpleDateFormat("yyyy-MM-dd_HH-mm-ss", Locale.getDefault())
        val timestamp = dateFormat.format(Date())
        val crashFile = File(crashDir, "crash_$timestamp.txt")

        crashFile.writeText(buildString {
            appendLine("=== TSS Party Crash Report ===")
            appendLine("Time: $timestamp")
            appendLine("Thread: ${thread.name}")
            appendLine("Exception: ${throwable.javaClass.name}")
            appendLine("Message: ${throwable.message}")
            appendLine()
            appendLine("=== Stack Trace ===")
            appendLine(stackTrace)
            appendLine()
            appendLine("=== Device Info ===")
            appendLine("Android Version: ${android.os.Build.VERSION.RELEASE}")
            appendLine("SDK: ${android.os.Build.VERSION.SDK_INT}")
            appendLine("Device: ${android.os.Build.MANUFACTURER} ${android.os.Build.MODEL}")
        })

        Log.d(TAG, "Crash log saved to: ${crashFile.absolutePath}")
    }
}
