/**
 * Prompt Builder Service
 *
 * Handles the construction of system prompts for the agent,
 * supporting various modes (standard, YOLO, custom) and
 * integrating external Markdown prompts.
 *
 * Moltbot Integration:
 * - Loads intro_hook.txt content and prepends to system prompt
 * - Supports project-level and global intro hooks
 */
import { logger } from "../utils/logger.js";
import { getErrorMessage } from "../errors/index.js";
import { getSystemPromptForMode, getPromptManager, autoSelectPromptId, } from "../prompts/index.js";
export class PromptBuilder {
    config;
    promptCacheManager;
    memory;
    moltbotHooksManager;
    constructor(config, promptCacheManager, memory, moltbotHooksManager) {
        this.config = config;
        this.promptCacheManager = promptCacheManager;
        this.memory = memory;
        this.moltbotHooksManager = moltbotHooksManager;
    }
    /**
     * Build the system prompt for the agent
     */
    async buildSystemPrompt(systemPromptId, modelName, customInstructions) {
        try {
            let systemPrompt;
            // Load Moltbot intro hook content (role/personality instructions)
            let introHookContent;
            if (this.moltbotHooksManager) {
                try {
                    const introManager = this.moltbotHooksManager.getIntroManager();
                    const introResult = await introManager.loadIntro();
                    if (introResult.content) {
                        introHookContent = introResult.content;
                        logger.debug(`Loaded intro hook from sources: ${introResult.sources.join(', ')}`);
                    }
                }
                catch (err) {
                    logger.warn("Failed to load intro hook", { error: getErrorMessage(err) });
                }
            }
            // Get memory context if enabled
            let memoryContext;
            if (this.config.memoryEnabled && this.memory) {
                try {
                    memoryContext = await this.memory.buildContext({
                        includeProject: true,
                        includePreferences: true,
                        includeRecentSummaries: true
                    });
                }
                catch (err) {
                    logger.warn("Failed to build memory context", { error: getErrorMessage(err) });
                }
            }
            if (systemPromptId && systemPromptId !== 'auto') {
                // Use external prompt system (new)
                const promptManager = getPromptManager();
                systemPrompt = await promptManager.buildSystemPrompt({
                    promptId: systemPromptId,
                    includeModelInfo: true,
                    includeOsInfo: true,
                    includeProjectContext: false, // Don't include by default (expensive)
                    includeToolPrompts: true,
                    userInstructions: customInstructions || undefined,
                    cwd: this.config.cwd,
                    modelName,
                    tools: ['view_file', 'str_replace_editor', 'create_file', 'search', 'bash', 'todo', 'reason'],
                    includeMemory: !!memoryContext,
                    memoryContext,
                });
                logger.debug(`Using system prompt: ${systemPromptId}`);
            }
            else if (systemPromptId === 'auto') {
                // Auto-select based on model alignment
                const autoId = autoSelectPromptId(modelName);
                const promptManager = getPromptManager();
                systemPrompt = await promptManager.buildSystemPrompt({
                    promptId: autoId,
                    includeModelInfo: true,
                    includeOsInfo: true,
                    userInstructions: customInstructions || undefined,
                    cwd: this.config.cwd,
                    modelName,
                    includeMemory: !!memoryContext,
                    memoryContext,
                });
                logger.debug(`Auto-selected prompt: ${autoId} (based on ${modelName})`);
            }
            else {
                // Use legacy system (current behavior)
                const promptMode = this.config.yoloMode ? "yolo" : "default";
                systemPrompt = getSystemPromptForMode(promptMode, this.config.morphEditorEnabled, this.config.cwd, customInstructions || undefined);
            }
            // Prepend intro hook content if available (Moltbot-style role injection)
            if (introHookContent) {
                systemPrompt = `# Role & Instructions (from intro_hook.txt)\n\n${introHookContent}\n\n---\n\n${systemPrompt}`;
                logger.debug("Prepended intro hook content to system prompt");
            }
            // Inject bootstrap context files (BOOTSTRAP.md, AGENTS.md, SOUL.md, etc.)
            try {
                const { BootstrapLoader } = await import('../context/bootstrap-loader.js');
                const bootstrap = await new BootstrapLoader().load(this.config.cwd);
                if (bootstrap.content) {
                    systemPrompt += '\n\n# Workspace Context\n\n' + bootstrap.content;
                    logger.debug(`Loaded bootstrap context from ${bootstrap.sources.length} file(s)`, {
                        sources: bootstrap.sources,
                        chars: bootstrap.tokenCount,
                        truncated: bootstrap.truncated,
                    });
                }
            }
            catch (err) {
                logger.warn("Failed to load bootstrap context", { error: getErrorMessage(err) });
            }
            // Cache system prompt for optimization
            this.promptCacheManager.cacheSystemPrompt(systemPrompt);
            return systemPrompt;
        }
        catch (error) {
            // Fallback to legacy prompt on error
            logger.warn("Failed to load custom prompt, using default", { error: getErrorMessage(error) });
            const promptMode = this.config.yoloMode ? "yolo" : "default";
            return getSystemPromptForMode(promptMode, this.config.morphEditorEnabled, this.config.cwd, customInstructions || undefined);
        }
    }
    /**
     * Update configuration
     */
    updateConfig(config) {
        this.config = { ...this.config, ...config };
    }
}
//# sourceMappingURL=prompt-builder.js.map