package com.ledgrab.android

import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.util.Log
import androidx.core.content.ContextCompat

/**
 * Starts the LedGrab capture service automatically on device boot and
 * after the app is updated.
 *
 * Autostart is best-effort and deliberately limited:
 *  - Requires root. MediaProjection consent cannot be granted silently,
 *    so we can't resume capture on unrooted boxes without the user
 *    walking up to the TV and tapping Start.
 *  - Gated behind [AutostartPrefs] so the user can opt out.
 *
 * Receivers declared with BOOT_COMPLETED must be fast — we hand off to
 * a foreground service within milliseconds and let the service do the
 * heavy lifting (Chaquopy bootstrap, pipeline setup).
 */
class BootReceiver : BroadcastReceiver() {

    override fun onReceive(context: Context, intent: Intent) {
        val action = intent.action
        Log.i(TAG, "Boot event: $action")

        if (action != Intent.ACTION_BOOT_COMPLETED
            && action != Intent.ACTION_LOCKED_BOOT_COMPLETED
            && action != Intent.ACTION_MY_PACKAGE_REPLACED
        ) {
            return
        }

        if (!AutostartPrefs(context).isEnabled) {
            Log.i(TAG, "Autostart disabled — skipping")
            return
        }

        // Cheap check first (no process spawn). The real `su -c id` probe
        // would block and may not complete before the OS reclaims us.
        if (!Root.looksRooted()) {
            Log.i(TAG, "Device not rooted — cannot autostart without MediaProjection consent")
            return
        }

        try {
            ContextCompat.startForegroundService(
                context,
                CaptureService.createRootIntent(context),
            )
            Log.i(TAG, "LedGrab capture service dispatched on boot")
        } catch (e: Exception) {
            Log.e(TAG, "Failed to start service on boot", e)
        }
    }

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