package com.example.hmg_qline.hmg_qline

import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.os.Build
import android.util.Log

/**
 * BroadcastReceiver that handles device boot events.
 * Starts the app automatically after device boot and schedules daily restart alarm.
 * Compatible with Android 14+ (API 34+) and older versions.
 */
class BootBroadcastReceiver : BroadcastReceiver() {

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

    override fun onReceive(context: Context, intent: Intent) {
        Log.d(TAG, "Received intent: ${intent.action}")

        if (intent.action == Intent.ACTION_BOOT_COMPLETED ||
            intent.action == "android.intent.action.QUICKBOOT_POWERON" ||
            intent.action == "com.htc.intent.action.QUICKBOOT_POWERON"
        ) {
            Log.d(TAG, "Boot completed detected - Android SDK: ${Build.VERSION.SDK_INT}")

            // Schedule the daily restart alarm first
            scheduleRestartAlarm(context)

            // Then start the foreground service to launch the app
            startAppViaForegroundService(context)
        }
    }

    /**
     * Schedule daily restart alarm at 00:15.
     * This ensures the alarm is set even if the app wasn't running before reboot.
     */
    private fun scheduleRestartAlarm(context: Context) {
        try {
            Log.d(TAG, "Scheduling daily restart alarm after boot")
            AlarmScheduler.scheduleRestartAlarm(context, 0, 15) // 00:15 (12:15 AM)
            Log.d(TAG, "Daily restart alarm scheduled successfully")
        } catch (e: Exception) {
            Log.e(TAG, "Error scheduling restart alarm after boot: ${e.message}")
        }
    }

    /**
     * Start the app via foreground service.
     * Uses different approach based on Android version for compatibility.
     */
    private fun startAppViaForegroundService(context: Context) {
        try {
            Log.d(TAG, "Starting BootForegroundService")
            val serviceIntent = Intent(context, BootForegroundService::class.java).apply {
                putExtra("source", "boot_completed")
            }

            // Use foreground service for Android 8.0+ (API 26+)
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                context.startForegroundService(serviceIntent)
            } else {
                context.startService(serviceIntent)
            }

            Log.d(TAG, "BootForegroundService started successfully")
        } catch (e: Exception) {
            Log.e(TAG, "Error starting foreground service: ${e.message}")

            // Fallback: try direct activity launch
            tryDirectActivityLaunch(context)
        }
    }

    /**
     * Fallback method to launch activity directly if service fails.
     */
    private fun tryDirectActivityLaunch(context: Context) {
        try {
            Log.d(TAG, "Attempting direct activity launch as fallback")
            val launchIntent = context.packageManager.getLaunchIntentForPackage(context.packageName)?.apply {
                addFlags(Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TOP)
                putExtra("launched_from_boot", true)
            }
            context.startActivity(launchIntent)
            Log.d(TAG, "Direct activity launch successful")
        } catch (fallbackError: Exception) {
            Log.e(TAG, "Direct activity launch also failed: ${fallbackError.message}")
        }
    }
}