/**
 * Email 插件 - 自动回复
 */

const { EMAIL_DEFAULTS } = require('./constants')

/**
 * 处理自动回复
 * @param {Object} emailPlugin - EmailPlugin 实例
 * @param {Object} args - 回复参数
 * @returns {Promise<Object>} 回复结果
 */
async function handleAutoReply(emailPlugin, args) {
  let { to, subject, body, from, _event, prompt, messageId, inReplyTo } = args

  // 优先使用传入的参数，如果没有则尝试从 _event 提取（兼容旧方式）
  if ((!to || !subject || !body) && _event) {
    // 兼容多种事件结构
    const email = _event.email || _event.data?.email || _event.data || {}
    to = to || email.from?.text || email.from || ''
    subject = subject || email.subject || ''
    body = body || email.text || email.body || ''
    messageId = messageId || email.messageId || email.uid
  }

  // 优先使用传入的 inReplyTo，否则用 messageId
  const replyTo = inReplyTo || messageId

  // 检查必要参数
  if (!to) {
    return { success: false, error: '缺少收件人地址（to）' }
  }
  if (!body) {
    return { success: false, error: '缺少邮件内容（body）' }
  }

  try {
    // 使用子 Agent 生成回复
    const replyAgent = emailPlugin._framework.createSubAgent({
      name: 'email_replier',
      role: '邮件自动回复助手，专注于生成专业、礼貌、简洁的邮件回复',
      parentTools: []
    })

    // 构建提示让 LLM 生成回复
    const finalPrompt = prompt || `你是一封邮件自动回复助手。请根据以下邮件内容，生成一封专业的回复邮件。

【原始邮件】
发件人: ${from || to}
主题: ${subject}
内容:
${body}

【要求】
1. 回复内容要针对邮件中的问题或内容进行回复
2. 语言要专业、礼貌、简洁
3. 只输出邮件正文内容，不要额外解释
4. 回复语言应与原邮件一致（如果原邮件是中文，则用中文回复）`

    // 等待 Agent 生成回复（带超时保护）
    const timeoutMs = args.timeout || EMAIL_DEFAULTS.timeout
    const timeoutPromise = new Promise((_, reject) => {
      setTimeout(() => reject(new Error(`AI回复生成超时（${timeoutMs / 1000}秒）`)), timeoutMs)
    })

    const replyPromise = replyAgent.chat(finalPrompt, { maxSteps: 3 })
    const replyResult = await Promise.race([replyPromise, timeoutPromise])

    // 提取回复内容
    let replyContent = ''
    if (typeof replyResult === 'string') {
      replyContent = replyResult.trim()
    } else if (replyResult && replyResult.content) {
      replyContent = replyResult.content.trim()
    } else if (replyResult && replyResult.message) {
      replyContent = replyResult.message.trim()
    } else {
      replyContent = JSON.stringify(replyResult).trim()
    }

    // 去掉思考过程标签
    replyContent = replyContent.replace(/<think>[\s\S]*?<\/think>/g, '').trim()

    if (!replyContent || replyContent.length < 5) {
      return { success: false, error: 'AI未能生成有效的回复内容' }
    }

    // 发送回复邮件
    const { sendEmail } = require('./handlers')
    const sendResult = await sendEmail(emailPlugin, {
      to: from || to,
      subject: `Re: ${subject}`,
      body: replyContent,
      inReplyTo: replyTo,
      references: replyTo ? [replyTo] : undefined
    })

    if (sendResult.success) {
      // 发送成功后，标记为已处理
      const emailData = _event?.email || _event?.data?.email || _event?.data || {}
      const msgId = messageId || emailData.messageId || emailData.uid
      if (msgId) {
        emailPlugin._processedEmails.add(msgId)
        emailPlugin._saveProcessedEmails()
        emailPlugin._log.info(`邮件已处理: ${msgId}`)

        // 24小时后从已处理列表中移除
        setTimeout(() => {
          emailPlugin._processedEmails.delete(msgId)
          emailPlugin._saveProcessedEmails()
        }, EMAIL_DEFAULTS.processedEmailTTL)
      }

      // 自动标记原邮件为已读
      // emailData.uid 是数字 UID，emailData.messageId 是字符串
      const emailUid = emailData.uid
      if (emailUid) {
        try {
          const { markAsRead } = require('./handlers')
          await markAsRead(emailPlugin, { uid: emailUid })  // 使用数字 uid
        } catch (err) {
          emailPlugin._log.warn(`自动标记已读失败: ${err.message}`)
        }
      }

      return {
        success: true,
        message: `自动回复已发送至 ${from || to}`,
        replyContent
      }
    } else {
      return { success: false, error: sendResult.error || '发送失败' }
    }
  } catch (err) {
    return { success: false, error: err.message }
  }
}

module.exports = {
  handleAutoReply
}
