/**
 * AskUser tool — ask the user a question during agentic execution.
 *
 * In interactive mode, this sends the question to the user via the
 * context's askUser callback. In non-interactive mode, it returns
 * a message indicating the question could not be delivered.
 */

export const definition = {
  name: 'AskUser',
  description: 'Ask the user a question during execution. Use when you need clarification, preferences, or decisions from the user.',
  input_schema: {
    type: 'object',
    properties: {
      question: {
        type: 'string',
        description: 'The question to ask the user'
      },
      options: {
        type: 'array',
        items: {
          type: 'object',
          properties: {
            label: { type: 'string', description: 'Display text for this option' },
            description: { type: 'string', description: 'Explanation of this option' }
          },
          required: ['label']
        },
        description: 'Optional list of choices for the user'
      },
      multiSelect: {
        type: 'boolean',
        description: 'Whether multiple options can be selected (default false)'
      }
    },
    required: ['question']
  }
};

export async function execute(input, context) {
  const { question, options, multiSelect } = input;

  if (!question) {
    return { content: 'Error: question is required', is_error: true };
  }

  // If context has an askUser callback, use it
  if (context.askUser && typeof context.askUser === 'function') {
    try {
      const answer = await context.askUser({
        question,
        options: options || [],
        multiSelect: multiSelect || false
      });
      return {
        content: typeof answer === 'string' ? answer : JSON.stringify(answer),
        is_error: false
      };
    } catch (err) {
      return {
        content: `Error asking user: ${err.message}`,
        is_error: true
      };
    }
  }

  // If context has a pendingQuestion mechanism (WebSocket-based)
  if (context.setPendingQuestion && typeof context.setPendingQuestion === 'function') {
    return new Promise((resolve) => {
      context.setPendingQuestion({
        question,
        options: options || [],
        multiSelect: multiSelect || false,
        resolve: (answer) => {
          resolve({
            content: typeof answer === 'string' ? answer : JSON.stringify(answer),
            is_error: false
          });
        },
        reject: (reason) => {
          resolve({
            content: `User declined: ${reason || 'No reason given'}`,
            is_error: true
          });
        }
      });
    });
  }

  // Non-interactive fallback
  return {
    content: `Cannot ask user (non-interactive mode). Question was: "${question}"`,
    is_error: true
  };
}
