import com.correx.core.artifacts.kind.ConfigArtifactKind
import com.correx.core.artifacts.kind.FileWrittenKind
import com.correx.core.artifacts.kind.JsonSchema
import com.correx.core.artifacts.kind.TypedArtifactSlot
import com.correx.core.context.model.ContextLayer
import com.correx.core.context.model.EntryRole
import com.correx.core.events.events.RefinementIterationEvent
import com.correx.core.events.events.RetryAttemptedEvent
import com.correx.core.events.types.ArtifactId
import com.correx.core.events.types.SessionId
import com.correx.core.events.types.StageId
import com.correx.core.events.types.TransitionId
import com.correx.core.events.events.RepoKnowledgeHit
import com.correx.core.kernel.orchestration.buildAgentInstructionsEntry
import com.correx.core.kernel.orchestration.buildArtifactKindVocabularyEntry
import com.correx.core.kernel.orchestration.buildProjectProfileEntry
import com.correx.core.kernel.orchestration.buildRelevantFilesEntry
import com.correx.core.kernel.orchestration.buildRetryFeedbackEntry
import com.correx.core.kernel.orchestration.criticArtifactIds
import com.correx.core.sessions.BoundAgentInstructions
import com.correx.core.sessions.BoundProjectProfile
import com.correx.core.transitions.graph.StageConfig
import com.correx.core.transitions.graph.TransitionEdge
import com.correx.core.transitions.graph.WorkflowGraph
import com.correx.testing.fixtures.EventFixtures.stored
import org.junit.jupiter.api.Assertions.assertEquals
import org.junit.jupiter.api.Assertions.assertNull
import org.junit.jupiter.api.Assertions.assertTrue
import org.junit.jupiter.api.Test

class ContextFeedbackTest {

    @Test
    fun `no retry events yields null`() {
        assertNull(buildRetryFeedbackEntry(emptyList(), StageId("impl")))
    }

    @Test
    fun `latest retry event for the stage becomes a labeled L1 system entry`() {
        val events = listOf(
            stored(payload = RetryAttemptedEvent(SessionId("s"), StageId("impl"), 1, 3, "old reason")),
            stored(payload = RetryAttemptedEvent(SessionId("s"), StageId("other"), 1, 3, "other stage")),
            stored(payload = RetryAttemptedEvent(SessionId("s"), StageId("impl"), 2, 3, "tests failed: NPE in FooTest")),
        )
        val entry = buildRetryFeedbackEntry(events, StageId("impl"))!!
        assertEquals("retryFeedback", entry.sourceType)
        assertEquals(ContextLayer.L1, entry.layer)
        assertEquals(EntryRole.SYSTEM, entry.role)
        assertTrue(entry.content.contains("Attempt 2 of 3"), "content: ${entry.content}")
        assertTrue(entry.content.contains("tests failed: NPE in FooTest"), "content: ${entry.content}")
    }

    @Test
    fun `retry entry for other stage is not returned for queried stage`() {
        val events = listOf(
            stored(payload = RetryAttemptedEvent(SessionId("s"), StageId("other"), 1, 3, "reason")),
        )
        assertNull(buildRetryFeedbackEntry(events, StageId("impl")))
    }

    @Test
    fun `project profile renders as single L0 entry`() {
        val entry = buildProjectProfileEntry(
            BoundProjectProfile(
                about = "Event-sourced kernel",
                conventions = listOf("no bare try-catch"),
                commands = mapOf("test" to "./gradlew check"),
            ),
        )
        assertEquals(ContextLayer.L0, entry.layer)
        assertEquals(EntryRole.SYSTEM, entry.role)
        assertTrue(entry.content.startsWith("## Project profile"), "content: ${entry.content}")
        assertTrue(entry.content.contains("- no bare try-catch"), "content: ${entry.content}")
        assertTrue(entry.content.contains("test: ./gradlew check"), "content: ${entry.content}")
    }

    @Test
    fun `project profile with only about renders without conventions or commands sections`() {
        val entry = buildProjectProfileEntry(
            BoundProjectProfile(
                about = "Simple project",
                conventions = emptyList(),
                commands = emptyMap(),
            ),
        )
        assertTrue(entry.content.contains("Simple project"), "content: ${entry.content}")
        assertTrue(!entry.content.contains("### Conventions"), "should not contain Conventions: ${entry.content}")
        assertTrue(!entry.content.contains("### Commands"), "should not contain Commands: ${entry.content}")
        assertEquals("projectProfile", entry.sourceType)
    }

    @Test
    fun `agent instructions render as single L0 entry`() {
        val entry = buildAgentInstructionsEntry(
            BoundAgentInstructions(
                sources = listOf("CLAUDE.md", "AGENTS.md"),
                content = "# CLAUDE.md\n\nbe careful\n\n# AGENTS.md\n\nuse tools",
            ),
        )
        assertEquals(ContextLayer.L0, entry.layer)
        assertEquals(EntryRole.SYSTEM, entry.role)
        assertEquals("agentInstructions", entry.sourceType)
        assertTrue(entry.content.contains("# CLAUDE.md"), "content: ${entry.content}")
        assertTrue(entry.content.contains("# AGENTS.md"), "content: ${entry.content}")
    }

    @Test
    fun `criticArtifactIds resolves the from-stage produces on a back-edge`() {
        val graph = graphWith(
            "implement" to producesSlots("patch"),
            "review" to producesSlots("review_report"),
        )
        val events = listOf(
            stored(payload = RefinementIterationEvent(SessionId("s"), "review->implement", 1, 3)),
        )
        assertEquals(setOf(ArtifactId("review_report")), criticArtifactIds(events, graph, StageId("implement")))
    }

    @Test
    fun `vocabulary entry enumerates kind ids and flags llm-emitted`() {
        val plain = ConfigArtifactKind(id = "plan", schema = JsonSchema(type = "object"), llmEmitted = false)
        val emitted = ConfigArtifactKind(id = "report", schema = JsonSchema(type = "object"), llmEmitted = true)
        val entry = buildArtifactKindVocabularyEntry(listOf(plain, emitted))
        assertEquals("artifactKindVocabulary", entry.sourceType)
        assertEquals(ContextLayer.L1, entry.layer)
        assertEquals(EntryRole.SYSTEM, entry.role)
        assertTrue(entry.content.contains("plan"), "content should contain plain id: ${entry.content}")
        assertTrue(entry.content.contains("report (llm-emitted)"), "content should flag llm-emitted: ${entry.content}")
    }

    @Test
    fun `buildRelevantFilesEntry produces L3 system entry with Relevant files header`() {
        val hits = listOf(
            RepoKnowledgeHit(path = "src/Parser.kt", text = "src/Parser.kt: Parser, Lexer", score = 0.9f),
            RepoKnowledgeHit(path = "src/Main.kt", text = "src/Main.kt: main", score = 0.7f),
        )
        val entry = buildRelevantFilesEntry(hits)
        assertEquals(ContextLayer.L3, entry.layer)
        assertEquals(EntryRole.SYSTEM, entry.role)
        assertEquals("relevantFiles", entry.sourceType)
        assertTrue(entry.content.startsWith("## Relevant files"), "content: ${entry.content}")
        assertTrue(entry.content.contains("src/Parser.kt"), "content: ${entry.content}")
    }

    @Test
    fun `no refinement events yields empty set`() {
        assertTrue(criticArtifactIds(emptyList(), graphWith(), StageId("implement")).isEmpty())
    }

    @Test
    fun `criticArtifactIds ignores events targeting a different stage`() {
        val graph = graphWith(
            "implement" to producesSlots("patch"),
            "review" to producesSlots("review_report"),
        )
        val events = listOf(
            stored(payload = RefinementIterationEvent(SessionId("s"), "review->other", 1, 3)),
        )
        assertTrue(criticArtifactIds(events, graph, StageId("implement")).isEmpty())
    }
}

private fun producesSlots(vararg names: String): List<TypedArtifactSlot> =
    names.map { TypedArtifactSlot(name = ArtifactId(it), kind = FileWrittenKind) }

private fun graphWith(vararg stages: Pair<String, List<TypedArtifactSlot>>): WorkflowGraph {
    val stageMap = stages.associate { (id, slots) ->
        StageId(id) to StageConfig(produces = slots)
    }.toMutableMap()
    if (stageMap.isEmpty()) stageMap[StageId("start")] = StageConfig()
    return WorkflowGraph(
        id = "test-graph",
        stages = stageMap,
        transitions = emptySet(),
        start = stageMap.keys.first(),
    )
}
