package com.correx.apps.server

import com.correx.core.events.events.ToolRequest
import com.correx.core.events.types.SessionId
import com.correx.core.events.types.StageId
import com.correx.core.events.types.ToolInvocationId
import com.correx.core.tools.contract.Tool
import com.correx.core.tools.contract.ToolExecutor
import com.correx.core.tools.contract.ToolResult
import org.slf4j.Logger
import java.nio.file.Path
import java.util.UUID

/**
 * Bootstraps the codebase-memory index for the boot workspace (#242): its search tools are dead on
 * arrival ("project not found or not indexed") until `index_repository` runs once against the repo,
 * and nothing in a workflow calls it. If a mounted MCP server advertises an `index_repository` tool
 * we invoke it here, at working-dir open, with the workspace root — through the normal ToolExecutor
 * path, so no special-casing.
 *
 * ponytail: single-workspace boot only, "fast" mode. When per-connection working dirs land, hang
 * this off the WS-open hook as one entry in a bootstrap registry; one action doesn't earn a registry
 * yet. "fast" skips similarity/semantic edges — quickest to ready; upgrade the mode if search recall
 * proves thin.
 */
internal suspend fun bootstrapCodebaseIndex(mcpTools: List<Tool>, workspaceRoot: Path, log: Logger) {
    val tool = mcpTools.firstOrNull { it.name.endsWith("__index_repository") } ?: return
    val executor = tool as? ToolExecutor ?: return
    val request = ToolRequest(
        invocationId = ToolInvocationId(UUID.randomUUID().toString()),
        sessionId = SessionId("boot"),
        stageId = StageId("boot"),
        toolName = tool.name,
        parameters = mapOf("repo_path" to workspaceRoot.toString(), "mode" to "fast"),
    )
    when (val result = executor.execute(request)) {
        is ToolResult.Success -> log.info("Indexed workspace into codebase-memory ({})", tool.name)
        is ToolResult.Failure -> log.warn("codebase-memory index bootstrap failed: {}", result.reason)
    }
}
