package top.yeij.cyrene.service

import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.util.Log
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.SupervisorJob
import kotlinx.coroutines.flow.firstOrNull
import kotlinx.coroutines.launch
import org.koin.core.context.GlobalContext
import top.yeij.cyrene.data.local.PreferencesDataStore
import top.yeij.cyrene.data.repository.ChatRepositoryImpl

class BootReceiver : BroadcastReceiver() {

    private val scope = CoroutineScope(SupervisorJob() + Dispatchers.IO)

    override fun onReceive(context: Context, intent: Intent) {
        if (intent.action != Intent.ACTION_BOOT_COMPLETED) return
        Log.i(TAG, "Boot completed, restoring background connection")

        scope.launch {
            try {
                // Wait a moment for Koin to initialize
                kotlinx.coroutines.delay(5000)

                val prefs: PreferencesDataStore = GlobalContext.get().get()
                val token = prefs.token.firstOrNull()
                if (token.isNullOrBlank()) {
                    Log.i(TAG, "No auth token, skipping auto-connect")
                    return@launch
                }

                // Start keep-alive service
                WebSocketKeepAliveService.start(context)

                // Always reconnect — session may be stale
                val repo: ChatRepositoryImpl = GlobalContext.get().get()
                repo.ensureConnected()
                Log.i(TAG, "Boot connection restored, connected=${repo.connectionState.value}")

                // Schedule periodic wake-up
                KeepAliveReceiver.schedule(context)

                Log.i(TAG, "Background connection restored")
            } catch (e: Throwable) {
                Log.e(TAG, "Failed to restore connection on boot: ${e.message}", e)
                // Fallback: still try to start the service
                try { WebSocketKeepAliveService.start(context) } catch (_: Exception) { }
            }
        }
    }

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