package com.rosetta.messenger.network

import kotlinx.coroutines.flow.StateFlow

/**
 * Minimal compatibility facade for legacy static call-sites.
 *
 * New code should use injected [ProtocolRuntime]/[ProtocolGateway] or [ProtocolRuntimeAccess] directly.
 */
@Deprecated(
    message = "Use injected ProtocolRuntime/ProtocolGateway or ProtocolRuntimeAccess directly."
)
object ProtocolManager {
    val state: StateFlow<ProtocolState>
        get() = runtime().state

    val debugLogs: StateFlow<List<String>>
        get() = runtime().debugLogs

    fun addLog(message: String) = runtime().addLog(message)

    fun send(packet: Packet) = runtime().send(packet)

    fun sendPacket(packet: Packet) = runtime().sendPacket(packet)

    fun waitPacket(packetId: Int, callback: (Packet) -> Unit) =
        runtime().waitPacket(packetId, callback)

    fun unwaitPacket(packetId: Int, callback: (Packet) -> Unit) =
        runtime().unwaitPacket(packetId, callback)

    fun requestIceServers() = runtime().requestIceServers()

    fun waitCallSignal(callback: (PacketSignalPeer) -> Unit): (Packet) -> Unit =
        runtime().waitCallSignal(callback)

    fun unwaitCallSignal(callback: (Packet) -> Unit) =
        runtime().unwaitCallSignal(callback)

    fun waitWebRtcSignal(callback: (PacketWebRTC) -> Unit): (Packet) -> Unit =
        runtime().waitWebRtcSignal(callback)

    fun unwaitWebRtcSignal(callback: (Packet) -> Unit) =
        runtime().unwaitWebRtcSignal(callback)

    fun waitIceServers(callback: (PacketIceServers) -> Unit): (Packet) -> Unit =
        runtime().waitIceServers(callback)

    fun unwaitIceServers(callback: (Packet) -> Unit) =
        runtime().unwaitIceServers(callback)

    fun getCachedUserInfo(publicKey: String): SearchUser? =
        runtime().getCachedUserInfo(publicKey)

    fun isAuthenticated(): Boolean = runtime().isAuthenticated()

    fun restoreAuthFromStoredCredentials(
        preferredPublicKey: String? = null,
        reason: String = "background_restore"
    ): Boolean = runtime().restoreAuthFromStoredCredentials(preferredPublicKey, reason)

    fun reconnectNowIfNeeded(reason: String = "foreground_resume") =
        runtime().reconnectNowIfNeeded(reason)

    fun sendCallSignal(
        signalType: SignalType,
        src: String = "",
        dst: String = "",
        sharedPublic: String = "",
        callId: String = "",
        joinToken: String = ""
    ) = runtime().sendCallSignal(signalType, src, dst, sharedPublic, callId, joinToken)

    fun sendWebRtcSignal(signalType: WebRTCSignalType, sdpOrCandidate: String) =
        runtime().sendWebRtcSignal(signalType, sdpOrCandidate)

    suspend fun resolveUserInfo(publicKey: String, timeoutMs: Long = 3000): SearchUser? =
        runtime().resolveUserInfo(publicKey, timeoutMs)

    private fun runtime(): ProtocolRuntimePort = ProtocolRuntimeAccess.get()
}
