package com.correx.apps.server.workspace

import java.nio.file.Files
import java.nio.file.Path
import kotlin.io.path.isRegularFile
import kotlin.io.path.name
import kotlin.io.path.relativeTo

/**
 * Lists workspace-relative file paths under a root for the TUI's `@` file-reference picker.
 *
 * Deliberately distinct from `RepoMapIndexer`: that one reads every file's *contents* to extract
 * symbols and only covers source/markdown extensions (it feeds project memory + context). The `@`
 * picker wants *all* file types, by path only, as cheaply as possible — so this never opens a file.
 * It does share the indexer's directory-ignore convention (skip any path segment in [ignoreDirs])
 * so both agree on what "the workspace" is. Results are sorted and capped to bound the reply.
 */
object WorkspaceFiles {

    val DEFAULT_IGNORE_DIRS = setOf(
        ".git", "node_modules", "build", "target", ".gradle", "dist", ".idea", ".correx", ".venv",
    )
    const val DEFAULT_LIMIT = 2000
    private const val MAX_DEPTH = 12

    fun list(
        root: Path,
        ignoreDirs: Set<String> = DEFAULT_IGNORE_DIRS,
        limit: Int = DEFAULT_LIMIT,
    ): List<String> {
        if (!Files.isDirectory(root)) return emptyList()
        val out = ArrayList<String>()
        Files.walk(root, MAX_DEPTH).use { stream ->
            val iter = stream.iterator()
            while (iter.hasNext()) {
                val path = iter.next()
                if (!path.isRegularFile()) continue
                val rel = path.relativeTo(root)
                if (rel.any { it.name in ignoreDirs }) continue
                out.add(rel.toString())
            }
        }
        out.sort()
        return out.take(limit)
    }
}
