package com.correx.core.kernel.orchestration

import kotlinx.coroutines.runBlocking
import org.junit.jupiter.api.Assertions.assertEquals
import org.junit.jupiter.api.Assertions.assertTrue
import org.junit.jupiter.api.Test
import java.nio.file.Path
import kotlin.io.path.createTempDirectory
import kotlin.io.path.writeText

class ProcessStaticAnalysisRunnerTest {

    private val runner = ProcessStaticAnalysisRunner()

    private fun script(dir: Path, name: String, body: String): String {
        val file = dir.resolve(name)
        file.writeText("#!/bin/sh\n$body\n")
        file.toFile().setExecutable(true)
        return "./$name"
    }

    @Test
    fun `clean command reports exit zero and captures output`() = runBlocking {
        val dir = createTempDirectory("sa-ok")
        val cmd = script(dir, "ok.sh", "echo all-good")
        val result = runner.run(dir, cmd)
        assertEquals(0, result.exitCode)
        assertTrue(result.output.contains("all-good"), "output: ${result.output}")
    }

    @Test
    fun `failing command reports nonzero exit and captures stderr`() = runBlocking {
        val dir = createTempDirectory("sa-fail")
        // stderr is merged into the captured output (redirectErrorStream).
        val cmd = script(dir, "bad.sh", "echo boom 1>&2\nexit 2")
        val result = runner.run(dir, cmd)
        assertEquals(2, result.exitCode)
        assertTrue(result.output.contains("boom"), "output: ${result.output}")
    }

    @Test
    fun `unrunnable command is a failure, not a silent pass`() = runBlocking {
        val dir = createTempDirectory("sa-missing")
        val result = runner.run(dir, "./does-not-exist-xyz")
        assertTrue(result.exitCode != 0, "exit: ${result.exitCode}")
    }

    @Test
    fun `blank command is a failure`() = runBlocking {
        val dir = createTempDirectory("sa-blank")
        val result = runner.run(dir, "   ")
        assertTrue(result.exitCode != 0, "exit: ${result.exitCode}")
    }

    @Test
    fun `static floor skips an unsupported filetype without failing`() = runBlocking {
        val dir = createTempDirectory("sa-skip")
        dir.resolve("Main.kt").writeText("fun main() = Unit")
        val result = runner.run(dir, "correx-static-floor -- Main.kt")
        assertEquals(0, result.exitCode)
        assertTrue(result.output.contains("skipped"), "output: ${result.output}")
    }

    @Test
    fun `static floor checks javascript syntax without project dependencies`() = runBlocking {
        val dir = createTempDirectory("sa-js")
        dir.resolve("broken.js").writeText("const = ;")
        val result = runner.run(dir, "correx-static-floor -- broken.js")
        assertTrue(result.exitCode != 0, "exit: ${result.exitCode}")
    }
}
