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 for handling scheduled app restart alarms.
 * This is triggered by AlarmManager at the scheduled time (e.g., 12:15 AM).
 * Compatible with Android 14+ (API 34+) and older versions.
 */
class RestartAlarmReceiver : BroadcastReceiver() {

    companion object {
        private const val TAG = "RestartAlarmReceiver"
        const val ACTION_SCHEDULED_RESTART = "com.example.hmg_qline.SCHEDULED_RESTART"
    }

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

        when (intent.action) {
            ACTION_SCHEDULED_RESTART -> {
                Log.d(TAG, "Scheduled restart triggered")
                launchApp(context)

                // Re-schedule the alarm for the next day
                rescheduleAlarm(context)
            }
            Intent.ACTION_BOOT_COMPLETED,
            "android.intent.action.QUICKBOOT_POWERON",
            "com.htc.intent.action.QUICKBOOT_POWERON" -> {
                Log.d(TAG, "Boot completed - re-scheduling daily restart alarm")
                rescheduleAlarm(context)
            }
        }
    }

    private fun launchApp(context: Context) {
        try {
            Log.d(TAG, "Launching app via foreground service")

            val serviceIntent = Intent(context, BootForegroundService::class.java).apply {
                putExtra("source", "scheduled_restart")
            }

            // 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, "App launch initiated successfully")
        } catch (e: Exception) {
            Log.e(TAG, "Error launching app: ${e.message}")

            // Fallback: try direct activity launch
            try {
                val launchIntent = context.packageManager.getLaunchIntentForPackage(context.packageName)?.apply {
                    addFlags(Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TOP)
                }
                context.startActivity(launchIntent)
            } catch (fallbackError: Exception) {
                Log.e(TAG, "Fallback launch also failed: ${fallbackError.message}")
            }
        }
    }

    private fun rescheduleAlarm(context: Context) {
        try {
            // Re-schedule for the next day at 00:15
            AlarmScheduler.scheduleRestartAlarm(context, 0, 15)
            Log.d(TAG, "Alarm rescheduled for next day at 00:15")
        } catch (e: Exception) {
            Log.e(TAG, "Error rescheduling alarm: ${e.message}")
        }
    }
}

