package com.example.hmg_qline.hmg_qline

import android.app.Notification
import android.app.NotificationChannel
import android.app.NotificationManager
import android.content.Intent
import android.content.pm.ServiceInfo
import android.os.Build
import android.util.Log
import androidx.core.app.NotificationCompat
import androidx.core.app.ServiceCompat
import androidx.lifecycle.LifecycleService

/**
 * Foreground service that launches the app after device boot or scheduled restart.
 * Compatible with Android 14+ (API 34+) and older versions.
 *
 * Android 14+ requires:
 * - Explicit foreground service type in manifest and code
 * - FOREGROUND_SERVICE_SPECIAL_USE permission
 */
class BootForegroundService : LifecycleService() {

    companion object {
        private const val TAG = "BootForegroundService"
        private const val CHANNEL_ID = "boot_service_channel"
        private const val NOTIFICATION_ID = 1
    }

    override fun onCreate() {
        super.onCreate()
        Log.d(TAG, "Service created - Android SDK: ${Build.VERSION.SDK_INT}")
        startForegroundServiceCompat()
    }

    override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
        super.onStartCommand(intent, flags, startId)

        val source = intent?.getStringExtra("source") ?: "unknown"
        Log.d(TAG, "Service started from source: $source")

        // Launch the main activity
        launchMainActivity(source)

        // Stop the service after launching the app
        stopSelf()

        return START_NOT_STICKY
    }

    /**
     * Start foreground service with Android version compatibility.
     * Android 14+ requires explicit foreground service type.
     */
    private fun startForegroundServiceCompat() {
        createNotificationChannel()

        val notification: Notification = NotificationCompat.Builder(this, CHANNEL_ID)
            .setContentTitle("QLine App")
            .setContentText("Starting QLine...")
            .setSmallIcon(R.mipmap.ic_launcher)
            .setPriority(NotificationCompat.PRIORITY_LOW)
            .setAutoCancel(true)
            .build()

        // Use ServiceCompat for Android 14+ compatibility
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.UPSIDE_DOWN_CAKE) {
            // Android 14+ (API 34+) requires explicit foreground service type
            ServiceCompat.startForeground(
                this,
                NOTIFICATION_ID,
                notification,
                ServiceInfo.FOREGROUND_SERVICE_TYPE_SPECIAL_USE
            )
            Log.d(TAG, "Foreground service started with SPECIAL_USE type (API 34+)")
        } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
            // Android 10-13 (API 29-33)
            startForeground(NOTIFICATION_ID, notification, ServiceInfo.FOREGROUND_SERVICE_TYPE_NONE)
            Log.d(TAG, "Foreground service started with NONE type (API 29-33)")
        } else {
            // Android 8-9 (API 26-28)
            startForeground(NOTIFICATION_ID, notification)
            Log.d(TAG, "Foreground service started (API 26-28)")
        }
    }

    /**
     * Launch the main activity.
     */
    private fun launchMainActivity(source: String) {
        try {
            Log.d(TAG, "Launching MainActivity from source: $source")

            val intent = Intent(this, MainActivity::class.java).apply {
                addFlags(Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TOP)
                putExtra("launched_from_boot", source == "boot_completed")
                putExtra("launched_from_scheduled_restart", source == "scheduled_restart")
            }
            startActivity(intent)

            Log.d(TAG, "MainActivity launched successfully")
        } catch (e: Exception) {
            Log.e(TAG, "Error launching MainActivity: ${e.message}")
        }
    }

    /**
     * Create notification channel for Android 8.0+ (API 26+).
     */
    private fun createNotificationChannel() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            val channel = NotificationChannel(
                CHANNEL_ID,
                "Boot Service Channel",
                NotificationManager.IMPORTANCE_LOW // Use LOW to avoid sound/vibration
            ).apply {
                description = "Used to start QLine app after device boot"
                setShowBadge(false)
            }

            val manager = getSystemService(NotificationManager::class.java)
            manager?.createNotificationChannel(channel)
            Log.d(TAG, "Notification channel created")
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        Log.d(TAG, "Service destroyed")
    }
}