const AVAILABLE_TOOLS_MARKER = "{{availableTools}}";
const GUIDELINES_MARKER = "{{guidelines}}";
function hasTemplateMarkers(systemPrompt) {
    return systemPrompt.includes(AVAILABLE_TOOLS_MARKER) || systemPrompt.includes(GUIDELINES_MARKER);
}
function buildAvailableTools(options) {
    const tools = options.selectedTools || ["read", "bash", "edit", "write"];
    const visibleTools = tools.filter((name) => !!options.toolSnippets?.[name]);
    if (visibleTools.length === 0)
        return "(none)";
    return visibleTools.map((name) => `- ${name}: ${options.toolSnippets[name]}`).join("\n");
}
function buildGuidelines(options) {
    const tools = options.selectedTools || ["read", "bash", "edit", "write"];
    const guidelinesList = [];
    const guidelinesSet = new Set();
    const addGuideline = (guideline) => {
        if (guidelinesSet.has(guideline))
            return;
        guidelinesSet.add(guideline);
        guidelinesList.push(guideline);
    };
    const hasBash = tools.includes("bash");
    const hasGrep = tools.includes("grep");
    const hasFind = tools.includes("find");
    const hasLs = tools.includes("ls");
    if (hasBash && !hasGrep && !hasFind && !hasLs) {
        addGuideline("Use bash for file operations like ls, rg, find");
    }
    else if (hasBash && (hasGrep || hasFind || hasLs)) {
        addGuideline("Prefer grep/find/ls tools over bash for file exploration (faster, respects .gitignore)");
    }
    for (const guideline of options.promptGuidelines ?? []) {
        const normalized = guideline.trim();
        if (normalized.length > 0)
            addGuideline(normalized);
    }
    addGuideline("Be concise in your responses");
    addGuideline("Show file paths clearly when working with files");
    return guidelinesList.map((guideline) => `- ${guideline}`).join("\n");
}
export function renderPiboSystemPromptTemplate(systemPrompt, options) {
    if (!hasTemplateMarkers(systemPrompt))
        return systemPrompt;
    return systemPrompt
        .replaceAll(AVAILABLE_TOOLS_MARKER, buildAvailableTools(options))
        .replaceAll(GUIDELINES_MARKER, buildGuidelines(options));
}
export function createPiboSystemPromptTemplateExtension() {
    return (pi) => {
        pi.on("before_agent_start", (event) => {
            const systemPrompt = renderPiboSystemPromptTemplate(event.systemPrompt, event.systemPromptOptions);
            return systemPrompt === event.systemPrompt ? undefined : { systemPrompt };
        });
    };
}
