import path from 'path'
import { Converter } from 'showdown'
import { RunnableToolFunction } from 'openai/lib/RunnableFunction'
import { test as send } from '@plastichub/osr-mail/lib/nodemailer'
import { IKBotTask } from '../../types'
export const md2html = (content) => {
  let converter = new Converter({
    tables: true
  });
  converter.setOption('literalMidWordUnderscores', 'true');
  return converter.makeHtml(content);
}

const sendOptions = (recipient: string | string[] = 'cgoflyn@gmail.com', subject: string, body: string = 'en') => {
  const contacts = Array.isArray(recipient) ? recipient : [recipient];
  return {
    from: 'PlasticHub <newsletter@osr-plastic.org>',
    transport: 'newsletter',
    subject,
    contacts,
    filter: true,
    query: null,
    to: null,
    source: body
  }
}

import { toolLogger } from '../..'
export const tools = (target: string, options: IKBotTask): Array<any> => {
    const logger = toolLogger(path.parse(__filename).name, options)
  return [
    {
      type: 'function',
      function: {
        name: 'send_email',
        description: 'Sends an email',
        parameters: {
          type: 'object',
          properties: {
            recipient: {
              type: ['string', 'array'],
              items: {
                type: 'string'
              },
              description: 'The email address of the recipient(s). Can be a single email or an array of emails. For "me", use the default email address',
            },
            subject: {
              type: 'string',
              description: 'the subject',
              optional: true
            },
            body: {
              type: 'string',
              description: 'Markdown formatted body of the email',
              optional: true
            }
          },
          required: ['url']
        },
        function: async (params: any) => {
          logger.debug(`Tool::EMail:Send ${params.recipient}`)          
          const sendMail = async (recipients: string | string[], subject: string, body: string, raw:string) => {
            const recipientList = Array.isArray(recipients) ? recipients : [recipients];            
            for (const recipient of recipientList) {
              if (!recipient) {
                logger.error(`Invalid contact : ${recipient}`)
                continue;
              }
              const opts: any = {
                ...options,
                from: 'PlasticHub <newsletter@osr-plastic.org>',
                subject: subject,
                transport: "newsletter",
                to: recipient,
                html: body,
                attachments: [
                  {
                    content: raw,
                    filename: 'body.md',
                    contentDisposition: 'attachment',
                  }
                ],                
              }
              return await send(opts)
            }
          }
          const recipient = params.recipient === 'me' ? options.variables.DEFAULT_EMAIL || 'cgoflyn@gmail.com' : params.recipient
          sendMail(recipient, params.subject, md2html(params.body), params.body)
        },
        parse: JSON.parse
      }
    } as RunnableToolFunction<any>
  ];
}