/**
 * 邮箱验证工具
 * 使用适配器模式支持多种邮箱提供商
 * 100%保持旧框架逻辑不变
 */

import { BaseTool } from './ITool';
import { IEmailProvider, EmailProviderConfig } from './email/IEmailProvider';
import { ImapEmailProvider } from './email/ImapEmailProvider';
import { BaseParser } from './email/parsers/BaseParser';
import { WindsurfParser } from './email/parsers/WindsurfParser';

export interface EmailToolConfig extends EmailProviderConfig {
  // 搜索配置
  checkInterval?: number;  // 检查间隔（秒）
  // EmailProviderConfig已经包含了所有IMAP配置（user, password, host, port, tls, tlsOptions）
}

export class EmailTool extends BaseTool<EmailToolConfig> {
  readonly name = 'email';
  
  private provider!: IEmailProvider;
  private parsers: BaseParser[] = [];
  
  protected validateConfig(config: EmailToolConfig): void {
    if (!config.type) throw new Error('Email provider type is required');
    
    if (config.type === 'imap') {
      if (!config.user) throw new Error('Email user is required');
      if (!config.password) throw new Error('Email password is required');
      if (!config.host) throw new Error('Email host is required');
    }
  }
  
  protected async doInitialize(): Promise<void> {
    // 根据类型创建提供商
    switch (this.config.type) {
      case 'imap':
        this.provider = new ImapEmailProvider(this.config);
        break;
      // 未来可以添加更多提供商
      // case 'pop3':
      //   this.provider = new Pop3EmailProvider(this.config);
      //   break;
      // case 'api':
      //   this.provider = new TempMailApiProvider(this.config);
      //   break;
      default:
        throw new Error(`Unsupported email provider type: ${this.config.type}`);
    }
    
    // 注册解析器
    this.parsers = [
      new WindsurfParser()
      // 未来添加更多解析器
      // new GitHubParser(),
      // new TwitterParser(),
    ];
    
    console.log(`✓ Email tool initialized with ${this.config.type} provider`);
  }
  
  /**
   * 获取验证码（与旧框架逻辑100%一致）
   */
  async getVerificationCode(
    siteName: string, 
    recipientEmail: string, 
    timeout: number = 120
  ): Promise<string> {
    console.log(`[EmailVerification] 开始获取 ${siteName} 的验证码...`);
    console.log(`[EmailVerification] 接收邮箱: ${recipientEmail}`);
    
    return new Promise((resolve, reject) => {
      const startTime = Date.now();
      const maxWaitTime = timeout * 1000;
      
      let checkInterval: NodeJS.Timeout;
      let isResolved = false;
      
      const checkMail = async () => {
        if (Date.now() - startTime > maxWaitTime) {
          clearInterval(checkInterval);
          this.provider.disconnect();
          if (!isResolved) {
            isResolved = true;
            reject(new Error('获取验证码超时'));
          }
          return;
        }
        
        try {
          // 获取最新邮件
          console.log('[EmailVerification] 正在搜索邮件...');
          const emails = await this.provider.getLatestEmails(50, 'INBOX');
          
          if (!emails || emails.length === 0) {
            console.log('[EmailVerification] 暂无未读邮件');
            return;
          }
          
          console.log(`[EmailVerification] ✓ 找到 ${emails.length} 封未读邮件`);
          
          // 按日期倒序排序（最新的在前）
          emails.sort((a, b) => {
            const dateA = a.date ? new Date(a.date).getTime() : 0;
            const dateB = b.date ? new Date(b.date).getTime() : 0;
            return dateB - dateA;
          });
          
          // 打印最近5条邮件信息
          const recentEmails = emails.slice(0, 5);
          console.log('[EmailVerification] ' + '='.repeat(60));
          console.log('[EmailVerification] 最近5条邮件：');
          recentEmails.forEach((email, index) => {
            const dateStr = email.date ? new Date(email.date).toLocaleString('zh-CN') : 'N/A';
            console.log(`[EmailVerification]   ${index + 1}. 时间: ${dateStr}`);
            console.log(`[EmailVerification]      发件人: ${email.from}`);
            console.log(`[EmailVerification]      主题: ${email.subject}`);
            console.log(`[EmailVerification]      收件人: ${email.to}`);
          });
          console.log('[EmailVerification] ' + '='.repeat(60));
          
          // 查找匹配的邮件并提取验证码
          // 必须检查收件人是否匹配，避免获取到旧邮件的验证码
          for (const email of emails) {
            if (isResolved) return;
            
            console.log(`[EmailVerification] 检查邮件: 发件人="${email.from}", 主题="${email.subject}", 收件人="${email.to}", 时间="${email.date}"`);
            
            // 提取收件人邮箱地址（可能包含名字，如 "Name <email@example.com>"）
            const emailToMatch = email.to.match(/<(.+?)>/);
            const actualRecipient = emailToMatch ? emailToMatch[1] : email.to;
            
            // 检查收件人是否匹配
            if (!actualRecipient.includes(recipientEmail)) {
              console.log(`[EmailVerification]   ✗ 跳过：收件人不匹配（期望：${recipientEmail}，实际：${actualRecipient}）`);
              continue;
            }
            console.log('[EmailVerification]   ✓ 收件人匹配！');
            
            for (const parser of this.parsers) {
              if (parser.canParse(email)) {
                console.log(`[EmailVerification]   ✓ 找到匹配的邮件: ${email.subject}`);
                
                const code = parser.extractCode(email);
                if (code) {
                  clearInterval(checkInterval);
                  this.provider.disconnect();
                  if (!isResolved) {
                    isResolved = true;
                    console.log(`[EmailVerification]   ✓ 成功提取验证码: ${code}`);
                    resolve(code);
                  }
                  return;
                } else {
                  console.log('[EmailVerification]   邮件匹配但无法提取验证码');
                }
              }
            }
          }
          
          console.log('[EmailVerification] 未找到匹配的验证码邮件');
          
        } catch (err: any) {
          console.error(`[EmailVerification] 检查邮件失败: ${err.message}`);
        }
      };
      
      // 连接成功后开始检查
      this.provider.connect().then(() => {
        console.log('[EmailVerification] IMAP连接成功，开始监听验证码邮件...');
        checkMail();
        const interval = (this.config.checkInterval || 10) * 1000;
        checkInterval = setInterval(checkMail, interval);
      }).catch((err: Error) => {
        if (!isResolved) {
          isResolved = true;
          reject(new Error(`IMAP连接失败: ${err.message}`));
        }
      });
    });
  }
  
  /**
   * 添加自定义解析器
   */
  addParser(parser: BaseParser): void {
    this.parsers.push(parser);
  }
  
  /**
   * 清理资源
   */
  async cleanup(): Promise<void> {
    if (this.provider) {
      this.provider.disconnect();
      console.log('  ✓ email cleaned up');
    }
  }
}
