package com.correx.core.events.serialization

import com.correx.core.events.events.AssessedIssue
import com.correx.core.events.events.EventPayload
import com.correx.core.events.events.ToolCallAssessedEvent
import com.correx.core.events.events.ToolCallObservation
import com.correx.core.events.risk.RiskAction
import com.correx.core.events.types.SessionId
import com.correx.core.events.types.StageId
import com.correx.core.events.types.ToolInvocationId
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertTrue

class ToolCallAssessedEventSerializationTest {

    private val sample = ToolCallAssessedEvent(
        invocationId = ToolInvocationId("inv-1"),
        sessionId = SessionId("sess-1"),
        stageId = StageId("stage-1"),
        toolName = "file_write",
        issues = listOf(AssessedIssue("PATH_OUTSIDE_WORKSPACE", "outside: /tmp/x", "WARNING")),
        observations = listOf(
            ToolCallObservation(
                ruleCode = "PATH_CONTAINMENT",
                facts = mapOf(
                    "path" to "/tmp/x",
                    "exists" to "false",
                    "inWorkspace" to "false",
                    "privileged" to "false",
                ),
            ),
        ),
        disposition = RiskAction.PROMPT_USER,
        timestampMs = 42L,
    )

    @Test
    fun `round-trips as polymorphic EventPayload`() {
        val encoded = eventJson.encodeToString(EventPayload.serializer(), sample)
        assertTrue(encoded.contains("\"type\":\"ToolCallAssessed\""), "SerialName must be present: $encoded")
        val decoded = eventJson.decodeFromString(EventPayload.serializer(), encoded)
        assertEquals(sample, decoded)
    }

    @Test
    fun `decodes hand-written ToolCallAssessed JSON`() {
        val json = """
            {"type":"ToolCallAssessed","invocationId":"inv-9","sessionId":"s","stageId":"st",
             "toolName":"shell","issues":[],"observations":[],"disposition":"PROCEED","timestampMs":1}
        """.trimIndent()
        val decoded = eventJson.decodeFromString(EventPayload.serializer(), json)
        assertTrue(decoded is ToolCallAssessedEvent)
        assertEquals(RiskAction.PROCEED, (decoded as ToolCallAssessedEvent).disposition)
    }
}
