package com.correx.core.config

import org.junit.jupiter.api.Assertions.assertEquals
import org.junit.jupiter.api.Assertions.assertFalse
import org.junit.jupiter.api.Assertions.assertTrue
import org.junit.jupiter.api.Test
import org.junit.jupiter.api.io.TempDir
import java.nio.file.Files
import java.nio.file.Path

class AgentInstructionsLoaderTest {

    @Test
    fun `AGENTS is loaded and CLAUDE is ignored`(@TempDir root: Path) {
        // CLAUDE.md is deliberately not an agent-instruction source: it targets the outer assistant
        // and polluted the stage context. Only AGENTS.md (the agent operating contract) is loaded.
        Files.writeString(root.resolve("CLAUDE.md"), "Claude rules")
        Files.writeString(root.resolve("AGENTS.md"), "Agents rules")

        val loaded = AgentInstructionsLoader.load(root.toString())

        assertEquals(listOf("AGENTS.md"), loaded.sources)
        assertTrue(loaded.content.contains("# AGENTS.md"), "content: ${loaded.content}")
        assertTrue(loaded.content.contains("Agents rules"), "content: ${loaded.content}")
        assertFalse(loaded.content.contains("Claude rules"), "content: ${loaded.content}")
        assertFalse(loaded.isEmpty())
    }

    @Test
    fun `only one file present yields that one`(@TempDir root: Path) {
        Files.writeString(root.resolve("AGENTS.md"), "Agents only")

        val loaded = AgentInstructionsLoader.load(root.toString())

        assertEquals(listOf("AGENTS.md"), loaded.sources)
        assertTrue(loaded.content.contains("# AGENTS.md"), "content: ${loaded.content}")
        assertTrue(loaded.content.contains("Agents only"), "content: ${loaded.content}")
        assertFalse(loaded.content.contains("CLAUDE.md"), "content: ${loaded.content}")
    }

    @Test
    fun `neither file present is empty`(@TempDir root: Path) {
        val loaded = AgentInstructionsLoader.load(root.toString())

        assertTrue(loaded.isEmpty())
        assertEquals(AgentInstructions(), loaded)
    }

    @Test
    fun `blank file is skipped`(@TempDir root: Path) {
        Files.writeString(root.resolve("CLAUDE.md"), "   \n  ")
        Files.writeString(root.resolve("AGENTS.md"), "Real content")

        val loaded = AgentInstructionsLoader.load(root.toString())

        assertEquals(listOf("AGENTS.md"), loaded.sources)
    }
}
