'use strict';

const EXTERNAL_ACTION_TOOLS = new Set([
  'calendar_create',
  'mail_reply',
  'mail_send',
  'notification',
  'reminder_create',
  'slack_send_message',
  'sms_send',
]);

const TOOL_CATEGORY_MATCHERS = Object.freeze([
  {
    test: /(?:^|[-_\s])bash(?:$|[-_\s])|shell|command/i,
    tools: new Set(['bash', 'bash command', 'run_shell']),
  },
  {
    test: /(?:^|[-_\s])edit(?:$|[-_\s])|write|patch/i,
    tools: new Set(['edit', 'edit_file', 'write_file', 'multi_edit', 'apply_patch']),
  },
  {
    test: /(?:^|[-_\s])read(?:$|[-_\s])|glob|grep|search/i,
    tools: new Set(['read', 'read_file', 'glob', 'grep_files', 'search_files', 'list_directory']),
  },
]);

function normalizeToolName(value) {
  return String(value || '').trim().toLowerCase();
}

function isWalleExternalActionTool(tool) {
  return EXTERNAL_ACTION_TOOLS.has(normalizeToolName(tool));
}

function shouldConsultLearnedApprovalRuleForWalle(rule = {}, tool = '') {
  const normalizedTool = normalizeToolName(tool);
  if (!normalizedTool) return false;
  if (isWalleExternalActionTool(normalizedTool)) return false;

  const categoryText = [
    rule.category,
    rule.label,
    rule.command_signature,
  ].filter(Boolean).join(' ');

  for (const matcher of TOOL_CATEGORY_MATCHERS) {
    if (!matcher.test.test(categoryText)) continue;
    return matcher.tools.has(normalizedTool);
  }

  return true;
}

module.exports = {
  EXTERNAL_ACTION_TOOLS,
  isWalleExternalActionTool,
  shouldConsultLearnedApprovalRuleForWalle,
};
