package com.cottondb.android.platformimport android.app.AlarmManagerimport android.content.BroadcastReceiverimport android.content.Contextimport android.content.Intentimport kotlinx.coroutines.CoroutineScopeimport kotlinx.coroutines.Dispatchersimport kotlinx.coroutines.SupervisorJobimport kotlinx.coroutines.launchimport kotlinx.coroutines.withTimeout/** The runtime handoff for a platform schedule change. */internalinterfaceScheduleChangeBoundary {/** Clears only requests Android loses at boot; alarm delivery history remains intact. */suspendfun clearBootClaims()/** Cancels every currently held local reminder before timezone-specific IDs are recomputed. */suspendfun cancelRemindersForTimeZoneChange()/** Cancels surviving exact-alarm PendingIntent identities without changing ledger history. */suspendfun cancelAlarmClaimsForAccessChange()/** Persists immediate and periodic reconciliation through the app-owned core runtime. */suspendfun enqueueReconciliation()}/** * Runs the required platform cleanup before requesting the one runtime-owned reconciliation pass. * It deliberately propagates failures: retrying with stale held rows would leave duplicate alerts. */internalsuspendfun handleScheduleChange( action: String, boundary: ScheduleChangeBoundary,) {when (action) {Intent.ACTION_BOOT_COMPLETED -> boundary.clearBootClaims()Intent.ACTION_TIMEZONE_CHANGED -> boundary.cancelRemindersForTimeZoneChange()AlarmManager.ACTION_SCHEDULE_EXACT_ALARM_PERMISSION_STATE_CHANGED -> { boundary.cancelAlarmClaimsForAccessChange() } } boundary.enqueueReconciliation()}/** * Hands platform schedule changes to the runtime-owned reconciliation job. It never opens core. * A timezone change cancels all reminder requests first because identifiers carry a local stamp; * their absolute moments can change while their identifiers do not. An exact-alarm access change * similarly clears surviving PendingIntent identities before reconciliation observes them as held. */classScheduleChangeReceiver : BroadcastReceiver() {overridefun onReceive(context: Context, intent: Intent) {val action = intent.action ?: returnif (action !in SCHEDULE_CHANGE_ACTIONS) returnval pending = goAsync() receiverScope.launch {try { withTimeout(RECEIVER_TIMEOUT_MILLIS) { handleScheduleChange(action, AndroidScheduleChangeBoundary(context.applicationContext)) } } catch (failure: Throwable) {AndroidReminderRuntime.report("Scheduled notifications could not be reconciled after a system schedule change.", failure, ) } finally { pending.finish() } } }companionobject {privateconstval RECEIVER_TIMEOUT_MILLIS = 8_000Lprivateval receiverScope = CoroutineScope(SupervisorJob() + Dispatchers.IO)privateval SCHEDULE_CHANGE_ACTIONS = setOf(Intent.ACTION_BOOT_COMPLETED,Intent.ACTION_TIME_CHANGED,Intent.ACTION_TIMEZONE_CHANGED,Intent.ACTION_MY_PACKAGE_REPLACED,AlarmManager.ACTION_SCHEDULE_EXACT_ALARM_PERMISSION_STATE_CHANGED, ) }}privateclassAndroidScheduleChangeBoundary(privateval context: Context,) : ScheduleChangeBoundary {privateval reminders = AndroidReminderCentre(context)overridesuspendfun clearBootClaims() { check(reminders.clearAfterBoot()) {"The reminder ledger could not be cleared after boot." }// This advances the boot generation but preserves signature, fire time and delivery state.AndroidAlarmLedgerStore(context).invalidateForCurrentBoot().getOrThrow() }overridesuspendfun cancelRemindersForTimeZoneChange() {val held = reminders.heldIdentifiers() reminders.cancel(held) }overridesuspendfun cancelAlarmClaimsForAccessChange() {val ledger = AndroidAlarmLedgerStore(context) ledger.exclusive {when (val read = ledger.read()) {AlarmLedgerRead.Missing -> UnitisAlarmLedgerRead.Available -> {val platform = AndroidExactAlarmPlatform(context) read.snapshot.entries.forEach { (id, entry) ->// An entry without a fire time is historical only; it has no PendingIntent.if (entry.firesAt != null) { platform.cancel( com.cottondb.android.day.alarms.androidAlarmKey(id), entry, ) } } }isAlarmLedgerRead.Unreadable -> error(read.message) } } }overridesuspendfun enqueueReconciliation() {AlarmDeliveryJob.ensurePeriodic(context)AlarmDeliveryJob.enqueue(context) }}