package com.correx.infrastructure.tools

import com.correx.core.approvals.Tier
import com.correx.core.events.EventDispatcher
import com.correx.core.events.events.EventPayload
import com.correx.core.events.events.NewEvent
import com.correx.core.events.events.StoredEvent
import com.correx.core.events.events.ToolExecutionFailedEvent
import com.correx.core.events.events.ToolRequest
import com.correx.core.events.stores.EventStore
import com.correx.core.events.types.SessionId
import com.correx.core.events.types.StageId
import com.correx.core.events.types.ToolInvocationId
import com.correx.core.tools.contract.ParamRole
import com.correx.core.tools.contract.Tool
import com.correx.core.tools.contract.ToolCapability
import com.correx.core.tools.contract.ToolExecutor
import com.correx.core.tools.contract.ToolResult
import com.correx.core.tools.contract.ValidationResult
import com.correx.core.tools.registry.ToolRegistry
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.emptyFlow
import kotlinx.coroutines.runBlocking
import kotlinx.serialization.json.JsonObject
import org.junit.jupiter.api.Assertions.assertEquals
import org.junit.jupiter.api.Assertions.assertTrue
import org.junit.jupiter.api.Test
import java.nio.file.Files

class SandboxedToolExecutorValidationTest {

    private class CapturingEventStore : EventStore {
        val payloads = mutableListOf<EventPayload>()
        override suspend fun append(event: NewEvent): StoredEvent {
            payloads += event.payload
            val seq = payloads.size.toLong()
            return StoredEvent(event.metadata, seq, seq, event.payload)
        }
        override suspend fun appendAll(events: List<NewEvent>): List<StoredEvent> = events.map { append(it) }
        override fun read(sessionId: SessionId): List<StoredEvent> = emptyList()
        override fun readFrom(sessionId: SessionId, fromSequence: Long): List<StoredEvent> = emptyList()
        override fun lastSequence(sessionId: SessionId): Long? = null
        override fun subscribe(sessionId: SessionId): Flow<StoredEvent> = emptyFlow()
        override fun subscribeAll(): Flow<StoredEvent> = emptyFlow()
        override suspend fun lastGlobalSequence(): Long = payloads.size.toLong()
        override fun allEvents(): Sequence<StoredEvent> = emptySequence()
        override fun allSessionIds(): Set<SessionId> = emptySet()
    }

    private class SingleToolRegistry(private val tool: Tool) : ToolRegistry {
        override fun resolve(name: String): Tool? = if (name == tool.name) tool else null
        override fun all(): List<Tool> = listOf(tool)
    }

    /** A tool that rejects every call at validation and would explode if execute() were reached. */
    private class AlwaysInvalidTool : Tool, ToolExecutor {
        override val name: String = "picky"
        override val description: String = "fake"
        override val tier: Tier = Tier.T2
        override val requiredCapabilities: Set<ToolCapability> = emptySet()
        override val paramRoles: Map<String, ParamRole> = emptyMap()
        override val parametersSchema: JsonObject = JsonObject(emptyMap())
        override fun validateRequest(request: ToolRequest): ValidationResult =
            ValidationResult.Invalid("Missing or empty 'argv' parameter. Expected List<String>.")
        override suspend fun execute(request: ToolRequest): ToolResult =
            error("execute must not run when validation fails")
    }

    @Test
    fun `bad args fail recoverably and never reach execute`() {
        val tool = AlwaysInvalidTool()
        val events = CapturingEventStore()
        val exec = SandboxedToolExecutor(
            delegate = tool,
            registry = SingleToolRegistry(tool),
            eventDispatcher = EventDispatcher(events),
            workDir = Files.createTempDirectory("sbx-validate"),
        )
        val result = runBlocking {
            exec.execute(ToolRequest(ToolInvocationId("inv"), SessionId("s"), StageId("st"), "picky", emptyMap()))
        }

        result as ToolResult.Failure
        assertTrue(result.recoverable, "validation failures must be recoverable so the model can correct + retry")
        // The executor surfaces the failure via the returned result; it does NOT emit
        // ToolExecutionFailedEvent — SessionOrchestrator is the single authoritative recorder of
        // tool completion/failure (avoids the double-emit that duplicated tool rows in the TUI).
        assertEquals(0, events.payloads.filterIsInstance<ToolExecutionFailedEvent>().size)
    }
}
