package com.correx.core.config

import java.nio.file.Files
import java.nio.file.Path
import java.nio.file.Paths

/**
 * Discovers standing agent instructions (`AGENTS.md`) at the bound workspace root only — no
 * parent walk, no nested lookup. Mirrors [ProjectProfileLoader]: the loaded snapshot is bound
 * as an event so replay reads the recorded fact, never the live file.
 *
 * CLAUDE.md is deliberately excluded: it targets the outer assistant (agent-dispatch / model-
 * selection guidance) and is noise to an in-workflow execution agent — injecting it bloated and
 * polluted the stage context. AGENTS.md holds the correx-agent operating contract (the numbered
 * how-to-finish-a-stage steps), which is what the agent actually needs.
 */
object AgentInstructionsLoader {
    private val FILE_NAMES = listOf("AGENTS.md")

    fun load(workspaceRoot: String): AgentInstructions {
        val sections = mutableListOf<String>()
        val sources = mutableListOf<String>()
        for (name in FILE_NAMES) {
            val contents = readIfPresent(Paths.get(workspaceRoot, name))
            if (contents == null || contents.isBlank()) continue
            sources.add(name)
            sections.add("# $name\n\n${contents.trim()}")
        }
        if (sections.isEmpty()) return AgentInstructions()
        return AgentInstructions(sources = sources, content = sections.joinToString("\n\n"))
    }

    private fun readIfPresent(path: Path): String? {
        if (!Files.exists(path)) return null
        return runCatching { Files.readString(path) }.getOrElse { e ->
            System.err.println("Warning: Failed to read agent instructions at $path: ${e.message}")
            null
        }
    }
}
