package com.correx.core.config

import org.junit.jupiter.api.Test
import org.junit.jupiter.api.Assertions.assertEquals
import org.junit.jupiter.api.Assertions.assertTrue
import java.nio.file.Files

class ProfileLoaderTest {

    private fun tempHome(): String {
        val dir = Files.createTempDirectory("correx-profile-test")
        val configDir = dir.resolve(".config/correx")
        Files.createDirectories(configDir)
        return dir.toString()
    }

    @Test
    fun `missing file returns default OperatorProfile`() {
        val home = tempHome()
        val profile = ProfileLoader.load(home)
        assertEquals(OperatorProfile(), profile)
    }

    @Test
    fun `file with about populates about field`() {
        val home = tempHome()
        val profileFile = java.nio.file.Paths.get(home, ".config", "correx", "profile.toml")
        Files.writeString(profileFile, """about = "I am a test operator"""")
        val profile = ProfileLoader.load(home)
        assertEquals("I am a test operator", profile.about)
    }

    @Test
    fun `file with preferences section populates preferred_models and conventions`() {
        val home = tempHome()
        val profileFile = java.nio.file.Paths.get(home, ".config", "correx", "profile.toml")
        Files.writeString(
            profileFile,
            """
            about = "tester"

            [preferences]
            approval_mode = "PROMPT"
            preferred_models = ["claude-3-opus", "claude-3-haiku"]
            conventions = ["use sealed classes", "no nullable returns"]
            """.trimIndent(),
        )
        val profile = ProfileLoader.load(home)
        assertEquals("tester", profile.about)
        assertEquals("PROMPT", profile.preferences.approvalMode)
        assertEquals(listOf("claude-3-opus", "claude-3-haiku"), profile.preferences.preferredModels)
        assertEquals(listOf("use sealed classes", "no nullable returns"), profile.preferences.conventions)
    }

    @Test
    fun `file with unknown fields does not crash`() {
        val home = tempHome()
        val profileFile = java.nio.file.Paths.get(home, ".config", "correx", "profile.toml")
        Files.writeString(
            profileFile,
            """
            about = "tester"
            unknown_field = "ignored"

            [preferences]
            approval_mode = "AUTO"
            mystery_key = 42

            [unknown_section]
            foo = "bar"
            """.trimIndent(),
        )
        val profile = ProfileLoader.load(home)
        assertEquals("tester", profile.about)
        assertEquals("AUTO", profile.preferences.approvalMode)
        assertTrue(profile.preferences.preferredModels.isEmpty())
    }
}
