package com.correx.core.events.serialization

import com.correx.core.events.events.EventPayload
import com.correx.core.events.events.TalkieNarrationEvent
import com.correx.core.events.types.SessionId
import com.correx.core.inference.TokenUsage
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertTrue

class TalkieNarrationEventSerializationTest {

    private val sample = TalkieNarrationEvent(
        sessionId = SessionId("sess-1"),
        narrationId = "narr-42",
        trigger = "stage_start",
        stageId = "stage-1",
        content = "Router chose the default path.",
        latencyMs = 123L,
        tokensUsed = TokenUsage(promptTokens = 10, completionTokens = 5),
        timestampMs = 1_700_000_000_000L,
    )

    @Test
    fun `round-trips as polymorphic EventPayload`() {
        val encoded = eventJson.encodeToString(EventPayload.serializer(), sample)
        // Wire discriminator is intentionally still "RouterNarration": the class was renamed
        // Router->Talkie, but changing a persisted @SerialName would break replay of existing logs.
        assertTrue(encoded.contains("\"type\":\"RouterNarration\""), "SerialName must be present: $encoded")
        val decoded = eventJson.decodeFromString(EventPayload.serializer(), encoded)
        assertEquals(sample, decoded)
    }

    @Test
    fun `round-trips with optional fields absent`() {
        val minimal = TalkieNarrationEvent(
            sessionId = SessionId("sess-2"),
            narrationId = "narr-0",
            trigger = "manual",
            content = "Minimal narration.",
            timestampMs = 1_000L,
        )
        val encoded = eventJson.encodeToString(EventPayload.serializer(), minimal)
        val decoded = eventJson.decodeFromString(EventPayload.serializer(), encoded)
        assertEquals(minimal, decoded)
    }
}
