package com.correx.infrastructure.workflow

import java.nio.file.Path
import kotlin.io.path.exists
import kotlin.io.path.readText

class FileSystemPromptLoader(
    private val configDir: Path = Path.of(System.getProperty("user.home"), ".config", "correx", "prompts"),
) : PromptLoader {
    override fun load(path: String): String {
        val expanded = expandTilde(path)
        val local = Path.of(expanded)
        if (local.exists()) return local.readText()

        val fromConfig = configDir.resolve(expanded)
        if (fromConfig.exists()) return fromConfig.readText()

        throw PromptNotFoundException("Prompt not found: $path (searched: $local, $fromConfig)")
    }

    // Expand a leading `~` / `~/...` to the user home so a config-supplied home path resolves
    // instead of being concatenated literally onto [configDir] (F-003).
    private fun expandTilde(path: String): String = when {
        path == "~" -> System.getProperty("user.home")
        path.startsWith("~/") -> System.getProperty("user.home") + path.substring(1)
        else -> path
    }
}
