package com.onthelevel

import android.app.Application
import android.content.Context
import com.onthelevel.core.billing.ProEntitlementRepository
import com.onthelevel.core.billing.StubProEntitlementRepository
import com.onthelevel.core.sensors.AndroidSensorSource
import com.onthelevel.core.sensors.SensorSource
import com.onthelevel.core.settings.SettingsRepository
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.SupervisorJob

/**
 * Manual application container — deliberately no DI framework for an app this size
 * (BRIEF.md §Sensor and measurement architecture).
 */
class AppContainer(context: Context) {
    private val appContext = context.applicationContext

    /**
     * Outlives any single screen. Used for durable fire-and-forget persistence
     * (e.g. saving a calibration): a screen-scoped coroutine would be cancelled if
     * the user leaves the moment the write is launched.
     *
     * Main.immediate (not Default) so writes launched from UI callbacks enqueue in
     * call order — two fast conflicting writes (recalibrate then Reset) then reach
     * DataStore deterministically. Only lightweight persistence runs here; DataStore
     * still performs the actual IO on its own dispatcher.
     */
    val applicationScope = CoroutineScope(SupervisorJob() + Dispatchers.Main.immediate)

    val sensorSource: SensorSource by lazy { AndroidSensorSource(appContext) }
    val settings: SettingsRepository by lazy { SettingsRepository(appContext) }
    val entitlement: ProEntitlementRepository by lazy { StubProEntitlementRepository() }
}

class OnTheLevelApp : Application() {
    val container: AppContainer by lazy { AppContainer(this) }
}
