import type { Tool, ToolResult } from '../types.js';
import type { ChannelRegistry } from '../../channels/registry.js';

interface MessageSendArgs {
  channel: string;
  peerId: string;
  text: string;
}

/**
 * Creates a message.send tool bound to the given ChannelRegistry.
 * Allows the agent to send messages to any registered channel.
 */
export function createMessageSendTool(channelRegistry: ChannelRegistry): Tool {
  return {
    name: 'message.send',
    description:
      'Send a message to a specific user on a specific channel. Use this to proactively reach out to users on Telegram, Discord, Slack, WhatsApp, or other connected channels.',
    inputSchema: {
      type: 'object',
      properties: {
        channel: {
          type: 'string',
          description: 'Channel adapter name (e.g. "telegram", "discord", "slack", "whatsapp", "webchat")',
        },
        peerId: {
          type: 'string',
          description: 'Target user or chat ID on the channel',
        },
        text: {
          type: 'string',
          description: 'Message text to send',
        },
      },
      required: ['channel', 'peerId', 'text'],
    },
    execute: async (rawArgs: unknown): Promise<ToolResult> => {
      const args = rawArgs as MessageSendArgs;

      try {
        const adapter = channelRegistry.get(args.channel);
        if (!adapter) {
          const available = channelRegistry.list().map((a) => a.name);
          return {
            success: false,
            output: '',
            error: `Channel "${args.channel}" not found. Available channels: ${available.join(', ')}`,
          };
        }

        if (adapter.status !== 'connected') {
          return {
            success: false,
            output: '',
            error: `Channel "${args.channel}" is not connected (status: ${adapter.status})`,
          };
        }

        await adapter.send(args.peerId, { text: args.text });
        return {
          success: true,
          output: `Message sent to ${args.peerId} on ${args.channel}.`,
        };
      } catch (error) {
        return {
          success: false,
          output: '',
          error: error instanceof Error ? error.message : String(error),
        };
      }
    },
  };
}
