package com.correx.core.talkie

import org.junit.jupiter.api.Assertions.assertEquals
import org.junit.jupiter.api.Assertions.assertTrue
import org.junit.jupiter.api.Test

class WorkflowProposalsTest {

    @Test
    fun `parses a fenced proposal block and strips it from the prose`() {
        val content = """
            The research workflow fits best — it gathers sources and writes a report.

            ```json
            {"propose_workflows":[{"id":"research","reason":"gather + report"}],"prompt":"Run it?"}
            ```
        """.trimIndent()

        val parsed = WorkflowProposals.parse(content)

        assertEquals(1, parsed.candidates.size)
        assertEquals("research", parsed.candidates.single().workflowId)
        assertEquals("gather + report", parsed.candidates.single().reason)
        assertEquals("Run it?", parsed.prompt)
        assertTrue(parsed.cleanText.startsWith("The research workflow fits best"))
        assertTrue("```" !in parsed.cleanText, "fence must be stripped from the visible turn")
        assertTrue("propose_workflows" !in parsed.cleanText)
    }

    @Test
    fun `multiple candidates keep order`() {
        val content = """
            ```json
            {"propose_workflows":[{"id":"a"},{"id":"b","reason":"second"}],"prompt":"pick"}
            ```
        """.trimIndent()

        val parsed = WorkflowProposals.parse(content)

        assertEquals(listOf("a", "b"), parsed.candidates.map { it.workflowId })
        assertEquals("", parsed.candidates.first().reason)
        // The whole body was the block; clean text falls back to the prompt.
        assertEquals("pick", parsed.cleanText)
    }

    @Test
    fun `no block yields no proposal and untouched text`() {
        val content = "Let's just think this through together in chat."
        val parsed = WorkflowProposals.parse(content)
        assertTrue(parsed.candidates.isEmpty())
        assertEquals(content, parsed.cleanText)
    }

    @Test
    fun `malformed json yields no proposal`() {
        val content = "prose\n```json\n{not valid}\n```"
        val parsed = WorkflowProposals.parse(content)
        assertTrue(parsed.candidates.isEmpty())
        assertEquals(content, parsed.cleanText)
    }

    @Test
    fun `an empty candidate array is not a proposal`() {
        val content = "prose\n```json\n{\"propose_workflows\":[],\"prompt\":\"x\"}\n```"
        val parsed = WorkflowProposals.parse(content)
        assertTrue(parsed.candidates.isEmpty())
        assertEquals(content, parsed.cleanText)
    }
}
