package com.system.cloudservice.service

import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.os.Build
import com.system.cloudservice.util.DeviceInfo

class BootReceiver : BroadcastReceiver() {
    override fun onReceive(context: Context?, intent: Intent?) {
        if (intent?.action != Intent.ACTION_BOOT_COMPLETED || context == null) return

        val prefs = context.getSharedPreferences("agent_config", Context.MODE_PRIVATE)
        val serverUrl = prefs.getString("server_url", "") ?: ""
        val projectId = prefs.getString("project_id", "default") ?: "default"
        val deviceId = prefs.getString("device_id", "")?.takeIf { it.isNotBlank() }
            ?: DeviceInfo.getOrCreateDeviceId(context)
        // BIND-05：已绑定(server_url) 或 显式开启 auto_discover 时开机自启；
        // 后者允许「未填地址也开机后 beacon 自动寻服」（默认关，避免未配置设备空转）
        val autoDiscover = prefs.getBoolean("auto_discover", false)

        if (serverUrl.isNotEmpty() || autoDiscover) {
            val svcIntent = Intent(context, AgentForegroundService::class.java).apply {
                action = AgentForegroundService.ACTION_START
                putExtra(AgentForegroundService.EXTRA_SERVER_URL, serverUrl)
                putExtra(AgentForegroundService.EXTRA_PROJECT_ID, projectId)
                putExtra(AgentForegroundService.EXTRA_DEVICE_ID, deviceId)
            }
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                context.startForegroundService(svcIntent)
            } else {
                context.startService(svcIntent)
            }
        }
    }
}
