import type { Tool, ToolResult } from '../types.js';
import type { OutboundAttachmentCollector } from '../../backends/native/attachments.js';

interface MediaSendArgs {
  data?: string;
  url?: string;
  mime_type: string;
  filename?: string;
}

/**
 * Create the media.send tool bound to an OutboundAttachmentCollector.
 *
 * The tool lets the agent queue a file or image to be sent back to the user.
 * Attachments are collected during the tool loop and included in the outbound
 * message after the agent finishes processing.
 */
export function createMediaSendTool(collector: OutboundAttachmentCollector): Tool {
  return {
    name: 'media.send',
    description:
      'Attach a file or image to send back to the user. The attachment will be included with the next text response.',
    inputSchema: {
      type: 'object',
      properties: {
        data: {
          type: 'string',
          description: 'Base64-encoded file content',
        },
        url: {
          type: 'string',
          description: 'URL to the file (alternative to data)',
        },
        mime_type: {
          type: 'string',
          description: 'MIME type of the file (e.g. image/png, application/pdf)',
        },
        filename: {
          type: 'string',
          description: 'Suggested filename',
        },
      },
      required: ['mime_type'],
    },

    execute: async (rawArgs: unknown): Promise<ToolResult> => {
      const args = rawArgs as MediaSendArgs;

      if (!args.data && !args.url) {
        return {
          success: false,
          output: '',
          error: 'Either data or url must be provided',
        };
      }

      collector.push({
        mimeType: args.mime_type,
        data: args.data,
        url: args.url,
        filename: args.filename,
      });

      const label = args.filename ? `: ${args.filename}` : '';
      return {
        success: true,
        output: `Attachment queued (${args.mime_type}${label})`,
      };
    },
  };
}
