package com.correx.infrastructure.workflow

import com.correx.core.kernel.orchestration.LspDiagnosticsRequest
import kotlinx.coroutines.runBlocking
import org.junit.jupiter.api.Assumptions.assumeTrue
import kotlin.io.path.createTempDirectory
import kotlin.io.path.writeText
import kotlin.test.Test
import kotlin.test.assertTrue

class Lsp4jRunnerLiveProof {
    @Test
    fun `push diagnostics catch a TS syntax error`(): Unit = runBlocking {
        assumeTrue(onPath("typescript-language-server"), "typescript-language-server not installed")
        val dir = createTempDirectory("lspproof")
        dir.resolve("broken.ts").writeText(
            """
            export const useArtifacts = () => {
              return 1
            // missing closing brace/semicolon
            const x: number = "string"
            """.trimIndent(),
        )
        val result = Lsp4jDiagnosticsRunner().pull(LspDiagnosticsRequest(dir, listOf("broken.ts")))
        println("skippedReason=${result.skippedReason} server=${result.server}")
        result.diagnostics.forEach { println("  ${it.line}:${it.character} ${it.severity} ${it.message}") }
        assertTrue(result.skippedReason == null, "gate must not skip: ${result.skippedReason}")
        assertTrue(result.diagnostics.any { it.severity == "error" }, "expected at least one error diagnostic")
    }

    private fun onPath(cmd: String): Boolean =
        System.getenv("PATH").orEmpty().split(':').any { java.io.File(it, cmd).canExecute() }
}
