package com.rosetta.messenger.network

import kotlinx.coroutines.CancellationException
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Job
import kotlinx.coroutines.channels.Channel
import kotlinx.coroutines.launch

class ProtocolConnectionSupervisor(
    private val scope: CoroutineScope,
    private val onEvent: suspend (ConnectionEvent) -> Unit,
    private val onError: (Throwable) -> Unit,
    private val addLog: (String) -> Unit
) {
    private val eventChannel = Channel<ConnectionEvent>(Channel.UNLIMITED)
    private val lock = Any()

    @Volatile private var job: Job? = null

    fun start() {
        if (job?.isActive == true) return
        synchronized(lock) {
            if (job?.isActive == true) return
            job =
                scope.launch {
                    for (event in eventChannel) {
                        try {
                            onEvent(event)
                        } catch (e: CancellationException) {
                            throw e
                        } catch (e: Exception) {
                            addLog("❌ ConnectionSupervisor event failed: ${e.message}")
                            onError(e)
                        }
                    }
                }
            addLog("🧠 ConnectionSupervisor started")
        }
    }

    fun post(event: ConnectionEvent) {
        start()
        val result = eventChannel.trySend(event)
        if (result.isFailure) {
            scope.launch { eventChannel.send(event) }
        }
    }
}
