package com.correx.infrastructure.workflow

import org.junit.jupiter.api.Test
import org.junit.jupiter.api.assertThrows
import java.nio.file.Files
import kotlin.io.path.writeText
import kotlin.test.assertContains
import kotlin.test.assertEquals

class FileSystemPromptLoaderTest {

    @Test
    fun `loads from absolute path when file exists`() {
        val file = Files.createTempFile("prompt", ".md").also { it.writeText("hello world") }
        val loader = FileSystemPromptLoader()
        assertEquals("hello world", loader.load(file.toAbsolutePath().toString()))
    }

    @Test
    fun `falls back to configDir when local path not found`() {
        val configDir = Files.createTempDirectory("correx-prompts")
        configDir.resolve("test.md").also { it.writeText("from config") }
        val loader = FileSystemPromptLoader(configDir = configDir)
        assertEquals("from config", loader.load("test.md"))
    }

    @Test
    fun `throws PromptNotFoundException with both paths when not found`() {
        val configDir = Files.createTempDirectory("correx-prompts-empty")
        val loader = FileSystemPromptLoader(configDir = configDir)
        val ex = assertThrows<PromptNotFoundException> { loader.load("missing.md") }
        assertContains(ex.message!!, "missing.md")
        assertContains(ex.message!!, configDir.toString())
    }

    @Test
    fun `expands leading tilde to user home (F-003)`() {
        val home = System.getProperty("user.home")
        val rel = "correx-tilde-${System.nanoTime()}.md"
        val file = java.nio.file.Path.of(home, rel).also { it.writeText("home prompt") }
        try {
            val loader = FileSystemPromptLoader(configDir = Files.createTempDirectory("unused"))
            assertEquals("home prompt", loader.load("~/$rel"))
        } finally {
            Files.deleteIfExists(file)
        }
    }

    @Test
    fun `local path takes precedence over configDir`() {
        val localFile = Files.createTempFile("prompt", ".md").also { it.writeText("local") }
        val configDir = Files.createTempDirectory("correx-prompts")
        configDir.resolve(localFile.fileName.toString()).also { it.writeText("from config") }

        val loader = FileSystemPromptLoader(configDir = configDir)
        assertEquals("local", loader.load(localFile.toAbsolutePath().toString()))
    }
}
