/**
 * Instruction Generator
 *
 * Creates phase-specific guidance for the LLM based on current conversation state.
 * Customizes instructions based on project context and development phase.
 * Supports custom state machine definitions for dynamic instruction generation.
 * Handles variable substitution for project artifact references.
 */
import { ProjectDocsManager } from './project-docs-manager.js';
export class InstructionGenerator {
    planManager;
    projectDocsManager;
    stateMachine = null;
    constructor(planManager) {
        this.planManager = planManager;
        this.projectDocsManager = new ProjectDocsManager();
    }
    /**
     * Set the state machine definition for dynamic instruction generation
     */
    setStateMachine(stateMachine) {
        this.stateMachine = stateMachine;
    }
    /**
     * Generate comprehensive instructions for the LLM
     */
    async generateInstructions(baseInstructions, context) {
        // Apply variable substitution to base instructions
        const substitutedInstructions = this.applyVariableSubstitution(baseInstructions, context.conversationContext.projectPath, context.conversationContext.gitBranch);
        // Get plan file guidance
        const planFileGuidance = this.planManager.generatePlanFileGuidance(context.phase);
        // Enhance base instructions with context-specific guidance
        const enhancedInstructions = await this.enhanceInstructions(substitutedInstructions, context, planFileGuidance);
        return {
            instructions: enhancedInstructions,
            planFileGuidance,
            metadata: {
                phase: context.phase,
                planFilePath: context.conversationContext.planFilePath,
                transitionReason: context.transitionReason,
                isModeled: context.isModeled,
            },
        };
    }
    /**
     * Apply variable substitution to instructions
     * Replaces project artifact variables with actual file paths
     */
    applyVariableSubstitution(instructions, projectPath, gitBranch) {
        const substitutions = this.projectDocsManager.getVariableSubstitutions(projectPath, gitBranch);
        let result = instructions;
        for (const [variable, value] of Object.entries(substitutions)) {
            // Use global replace to handle multiple occurrences
            result = result.replace(new RegExp(this.escapeRegExp(variable), 'g'), value);
        }
        return result;
    }
    /**
     * Escape special regex characters in variable names
     */
    escapeRegExp(string) {
        return string.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
    }
    /**
     * Enhance base instructions with context-specific information
     */
    async enhanceInstructions(baseInstructions, context, _planFileGuidance) {
        const { phase, conversationContext, transitionReason, isModeled, planFileExists, } = context;
        // Build plan-file-referential instructions
        let enhanced = `Check your plan file at \`${conversationContext.planFilePath}\` and focus on the "${this.capitalizePhase(phase)}" section.

${baseInstructions}

**Plan File Guidance:**
- Work on the tasks listed in the ${this.capitalizePhase(phase)} section
- Mark completed tasks with [x] as you finish them
- Add new tasks as they are identified during your work with the user
- Update the "Key Decisions" section with important choices made
- Add relevant notes to help maintain context`;
        // Add project context
        enhanced += `\n\n**Project Context:**
- Project: ${conversationContext.projectPath}
- Branch: ${conversationContext.gitBranch}
- Current Phase: ${phase}`;
        // Add transition context if this is a modeled transition
        if (isModeled && transitionReason) {
            enhanced += `\n\n**Phase Context:**
- ${transitionReason}`;
        }
        // Add plan file creation note if needed
        if (!planFileExists) {
            enhanced +=
                '\n\n**Note**: Plan file will be created when you first update it.';
        }
        // Add continuity and task management instructions
        enhanced += `\n\n**Important Reminders:**
- Use ONLY the development plan for task management - do not use your own task management tools
- Call whats_next() after the next user message to maintain the development workflow`;
        return enhanced;
    }
    /**
     * Capitalize phase name for display
     */
    capitalizePhase(phase) {
        return phase
            .split('_')
            .map(word => word.charAt(0).toUpperCase() + word.slice(1))
            .join(' ');
    }
}
//# sourceMappingURL=instruction-generator.js.map