package com.correx.apps.server.bridge

import com.correx.apps.server.protocol.ServerMessage
import com.correx.core.artifactstore.ArtifactStore
import com.correx.core.events.events.ChatSessionStartedEvent
import com.correx.core.events.events.ChatTurnEvent
import com.correx.core.events.events.SessionNamedEvent
import com.correx.core.events.events.SessionWorkspaceBoundEvent
import com.correx.core.events.events.StoredEvent
import com.correx.core.events.events.WorkflowCompletedEvent
import com.correx.core.events.events.WorkflowFailedEvent
import com.correx.core.events.events.WorkflowStartedEvent

/** Session lifecycle + chat-turn events. [artifactStore] is unused here but kept for a uniform mapper signature. */
@Suppress("UnusedParameter", "LongMethod")
internal suspend fun mapSessionEvent(
    event: StoredEvent,
    artifactStore: ArtifactStore,
    sessionSequence: Long,
): MapOutcome {
    val seq = event.sequence
    val msg = when (val p = event.payload) {
        is ChatSessionStartedEvent -> ServerMessage.SessionAnnounced(
            sessionId = p.sessionId,
            workflowId = "chat",
            sequence = seq,
            sessionSequence = sessionSequence,
        )

        is WorkflowStartedEvent -> ServerMessage.SessionAnnounced(
            sessionId = p.sessionId,
            workflowId = p.workflowId,
            sequence = seq,
            sessionSequence = sessionSequence,
        )

        is SessionWorkspaceBoundEvent -> ServerMessage.SessionWorkspaceBound(
            sessionId = p.sessionId,
            workspaceRoot = p.workspaceRoot,
            sequence = seq,
            sessionSequence = sessionSequence,
        )

        is SessionNamedEvent -> ServerMessage.SessionRenamed(
            sessionId = p.sessionId,
            name = p.name,
            sequence = seq,
            sessionSequence = sessionSequence,
        )

        is ChatTurnEvent -> ServerMessage.ChatTurn(
            sessionId = p.sessionId,
            turnId = p.turnId,
            role = p.role.name,
            content = p.content,
            latencyMs = p.latencyMs,
            totalTokens = p.tokensUsed?.totalTokens,
            sequence = seq,
            sessionSequence = sessionSequence,
        )

        is WorkflowCompletedEvent -> ServerMessage.SessionCompleted(
            sessionId = p.sessionId,
            sequence = seq,
            sessionSequence = sessionSequence,
        )

        is WorkflowFailedEvent -> ServerMessage.SessionFailed(
            sessionId = p.sessionId,
            reason = p.reason,
            sequence = seq,
            sessionSequence = sessionSequence,
        )

        else -> return MapOutcome.Skip
    }
    return MapOutcome.Emit(msg)
}
