/**
 * Tool execution engine for the agentic loop.
 *
 * Given a tool_use block from the API response, finds and executes
 * the matching tool, returning a tool_result.
 */

export async function executeToolUse(toolUse, executors, context = {}) {
  const { name, input, id } = toolUse;

  if (!name) {
    return { content: 'Error: tool_use block has no name', is_error: true };
  }

  const executor = executors.get(name);
  if (!executor) {
    return { content: `Unknown tool: "${name}". Available tools: ${[...executors.keys()].join(', ')}`, is_error: true };
  }

  // Run PreToolUse hook if hooks are available
  if (context.runPreToolUse) {
    try {
      const hookResult = await context.runPreToolUse(name, input, context);
      if (hookResult && !hookResult.allowed) {
        return {
          content: `Blocked by hook: ${hookResult.reason || 'PreToolUse hook denied execution'}`,
          is_error: true
        };
      }
      // Use modified input if hook provided one
      if (hookResult?.modifiedInput) {
        Object.assign(input, hookResult.modifiedInput);
      }
    } catch (err) {
      // Hook errors are non-fatal — log and continue
      console.error(`[executor] PreToolUse hook error for ${name}: ${err.message}`);
    }
  }

  // Check plan mode restrictions
  if (context.planMode && ['Write', 'Edit', 'MultiEdit', 'Bash'].includes(name)) {
    return {
      content: `Tool "${name}" is not available in plan mode. Exit plan mode first.`,
      is_error: true
    };
  }

  try {
    const result = await executor(input || {}, context);

    // Run PostToolUse hook
    if (context.runPostToolUse) {
      try {
        await context.runPostToolUse(name, input, result, context);
      } catch {
        // PostToolUse hook errors are non-fatal
      }
    }

    return {
      content: typeof result.content === 'string' ? result.content : JSON.stringify(result.content),
      is_error: result.is_error || false
    };
  } catch (err) {
    return {
      content: `Tool "${name}" threw an error: ${err.message}`,
      is_error: true
    };
  }
}
