package com.bytelyst.platform

import android.content.Context

/**
 * Unified entry point for the ByteLyst platform SDK.
 *
 * Creates and wires all platform services from a single config + context.
 * Mirrors the Swift `ByteLystPlatform` API.
 *
 * Usage:
 * ```kotlin
 * val platform = ByteLystPlatform(
 *     context = applicationContext,
 *     config = BLPlatformConfig(
 *         productId = "chronomind",
 *         baseUrl = "https://api.chronomind.app",
 *         applicationId = "com.chronomind.app"
 *     )
 * )
 *
 * platform.start()
 * platform.telemetry.trackScreen("home")
 * val isNew = platform.flags.isEnabled("new_feature")
 * platform.stop()
 * ```
 */
class ByteLystPlatform(
    context: Context,
    val config: BLPlatformConfig,
) {
    /** Secure storage (EncryptedSharedPreferences). */
    val secureStore: BLSecureStore = BLSecureStore(context, config.applicationId)

    /** HTTP client shared by services that need a token provider. */
    val client: BLPlatformClient = BLPlatformClient(config) {
        secureStore.read("access_token")
    }

    /** Auth client (login, register, refresh, MFA, etc.). */
    val auth: BLAuthClient = BLAuthClient(config, secureStore)

    /** Telemetry event tracking + batch flush. */
    val telemetry: BLTelemetryClient = BLTelemetryClient(config, context)

    /** Feature flag polling. */
    val flags: BLFeatureFlagClient = BLFeatureFlagClient(config)

    /** Kill switch checker. */
    val killSwitch: BLKillSwitchClient = BLKillSwitchClient(config)

    /** Local rotating audit log. */
    val auditLog: BLAuditLogger = BLAuditLogger(context, config)

    /** Whether [start] has been called. */
    var isStarted: Boolean = false
        private set

    /**
     * Start all services: telemetry flush timer, feature flag polling.
     * Call on app launch / Activity.onCreate.
     */
    fun start(userId: String? = null) {
        if (isStarted) return
        isStarted = true
        telemetry.start()
        flags.init(userId)
    }

    /**
     * Stop all services: flush telemetry, stop flag polling.
     * Call on app background / Activity.onDestroy.
     */
    fun stop() {
        if (!isStarted) return
        isStarted = false
        telemetry.stop()
        flags.stop()
    }
}
