package com.correx.apps.server.registry

import com.correx.infrastructure.workflow.TomlWorkflowLoader
import org.junit.jupiter.api.Test
import org.junit.jupiter.api.io.TempDir
import java.nio.file.Path
import kotlin.io.path.writeText
import kotlin.test.assertEquals
import kotlin.test.assertTrue

class FileSystemWorkflowRegistryTest {

    @TempDir
    lateinit var dir: Path

    private val validToml = """
        id = "healthcheck"
        start = "collect"
        description = "Runs the health check pipeline"

        [[stages]]
        id = "collect"
        prompt = "prompts/collect.md"
        produces = [{ name = "system_stats", kind = "file_written" }]
        allowed_tools = ["ShellTool"]
        token_budget = 2048
        max_retries = 2

        [[stages]]
        id = "report"
        prompt = "prompts/report.md"
        needs = ["system_stats"]
        produces = [{ name = "report", kind = "file_written" }]
        token_budget = 2048

        [[transitions]]
        id = "collect-to-report"
        from = "collect"
        to = "report"
        condition_type = "artifact_present"
        condition_artifact_id = "system_stats"

        [[transitions]]
        id = "report-to-done"
        from = "report"
        to = "done"
        condition_type = "always_true"
    """.trimIndent()

    @Test
    fun `listAll returns description from toml`() {
        dir.resolve("healthcheck.toml").writeText(validToml)
        val summaries = FileSystemWorkflowRegistry(TomlWorkflowLoader(), dir).listAll()
        assertEquals("Runs the health check pipeline", summaries.single().description)
    }

    @Test
    fun `listAll falls back to workflowId when description absent`() {
        val noDescToml = validToml.replace("description = \"Runs the health check pipeline\"\n", "")
        dir.resolve("healthcheck.toml").writeText(noDescToml)
        val registry = FileSystemWorkflowRegistry(TomlWorkflowLoader(), dir)
        assertEquals("healthcheck", registry.listAll().single().description)
    }

    @Test
    fun `listAll returns stageIds for each workflow`() {
        dir.resolve("healthcheck.toml").writeText(validToml)
        assertTrue(
            FileSystemWorkflowRegistry(TomlWorkflowLoader(), dir).listAll().single()
                .stageIds.containsAll(listOf("collect", "report")),
        )
    }
}
