package com.rosetta.messenger.network.connection

import com.rosetta.messenger.network.ConnectionBootstrapContext
import com.rosetta.messenger.network.ConnectionLifecycleState
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow

class RuntimeLifecycleStateMachine(
    private val bootstrapCoordinator: BootstrapCoordinator,
    private val addLog: (String) -> Unit
) {
    private val _connectionLifecycleState =
        MutableStateFlow(ConnectionLifecycleState.DISCONNECTED)
    val connectionLifecycleState: StateFlow<ConnectionLifecycleState> =
        _connectionLifecycleState.asStateFlow()

    var bootstrapContext: ConnectionBootstrapContext = ConnectionBootstrapContext()

    fun currentState(): ConnectionLifecycleState = _connectionLifecycleState.value

    fun recompute(reason: String) {
        val nextState =
            bootstrapCoordinator.recomputeLifecycleState(
                context = bootstrapContext,
                currentState = _connectionLifecycleState.value,
                reason = reason
            ) { state, updateReason ->
                if (_connectionLifecycleState.value == state) return@recomputeLifecycleState
                addLog(
                    "🧭 CONNECTION STATE: ${_connectionLifecycleState.value} -> $state ($updateReason)"
                )
                _connectionLifecycleState.value = state
            }
        _connectionLifecycleState.value = nextState
    }
}
