/**
 * 账号生成器工具 - 完整迁移自旧框架
 * 保持100%兼容
 */

import { BaseTool } from './ITool';

export interface AccountGeneratorConfig {
  email?: {
    domain?: string;
    pattern?: string;
  };
  password?: {
    strategy?: 'email' | 'random';
    length?: number;
    includeUppercase?: boolean;
    includeLowercase?: boolean;
    includeNumbers?: boolean;
    includeSpecial?: boolean;
  };
  name?: {
    gender?: 'male' | 'female' | 'neutral';
    locale?: 'en' | 'zh-CN';
  };
  phone?: {
    country?: string;
  };
  includePhone?: boolean;
}

export interface AccountData {
  firstName: string;
  lastName: string;
  fullName: string;
  email: string;
  username: string;
  password: string;
  passwordStrategy: string;
  timestamp: string;
  phone?: string;
}

export class AccountGeneratorTool extends BaseTool<AccountGeneratorConfig> {
  readonly name = 'account-generator';
  
  // 邮箱域名（与旧框架一致）
  private emailDomains = ['qichen111.asia'];
  
  // 英文名字库（与旧框架一致）
  private firstNames = {
    male: [
      'James', 'John', 'Robert', 'Michael', 'William',
      'David', 'Richard', 'Joseph', 'Thomas', 'Charles',
      'Daniel', 'Matthew', 'Anthony', 'Mark', 'Donald',
      'Steven', 'Paul', 'Andrew', 'Joshua', 'Kenneth'
    ],
    female: [
      'Mary', 'Patricia', 'Jennifer', 'Linda', 'Elizabeth',
      'Barbara', 'Susan', 'Jessica', 'Sarah', 'Karen',
      'Nancy', 'Lisa', 'Betty', 'Margaret', 'Sandra',
      'Ashley', 'Kimberly', 'Emily', 'Donna', 'Michelle'
    ],
    neutral: [
      'Alex', 'Jordan', 'Taylor', 'Casey', 'Riley',
      'Morgan', 'Parker', 'Avery', 'Quinn', 'Skyler'
    ]
  };
  
  // 姓氏库（与旧框架一致）
  private lastNames = [
    'Smith', 'Johnson', 'Williams', 'Brown', 'Jones',
    'Garcia', 'Miller', 'Davis', 'Rodriguez', 'Martinez',
    'Hernandez', 'Lopez', 'Gonzalez', 'Wilson', 'Anderson',
    'Thomas', 'Taylor', 'Moore', 'Jackson', 'Martin',
    'Lee', 'Perez', 'Thompson', 'White', 'Harris',
    'Sanchez', 'Clark', 'Ramirez', 'Lewis', 'Robinson'
  ];
  
  // 中文名字
  private chineseFirstNames = ['伟', '芳', '娜', '秀英', '敏', '静', '丽', '强', '磊', '军'];
  private chineseLastNames = ['王', '李', '张', '刘', '陈', '杨', '赵', '黄', '周', '吴'];
  
  // 密码字符集
  private lowercase = 'abcdefghijklmnopqrstuvwxyz';
  private uppercase = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
  private numbers = '0123456789';
  private special = '!@#$%^&*()_+-=[]{}|;:,.<>?';
  
  protected validateConfig(config: AccountGeneratorConfig): void {
    // 所有配置都是可选的
  }
  
  protected async doInitialize(): Promise<void> {
    // 设置默认配置
    this.config = this.config || {};
  }
  
  /**
   * 生成完整的账号数据（与旧框架接口一致）
   */
  async generate(options: AccountGeneratorConfig = {}): Promise<AccountData> {
    this.ensureInitialized();
    
    // 合并配置
    const opts = { ...this.config, ...options };
    
    // 生成名字
    const name = this.generateName(opts.name);
    
    // 生成邮箱
    const email = this.generateEmail(opts.email);
    
    // 生成密码（根据策略）
    let password: string;
    const passwordStrategy = opts.password?.strategy || 'email';
    if (passwordStrategy === 'email') {
      password = email;
    } else {
      password = this.generatePassword(opts.password);
    }
    
    // 生成用户名
    const username = this.generateUsername();
    
    const account: AccountData = {
      firstName: name.firstName,
      lastName: name.lastName,
      fullName: name.fullName,
      email,
      username,
      password,
      passwordStrategy,
      timestamp: new Date().toISOString()
    };
    
    // 可选：电话号码
    if (opts.includePhone !== false) {
      account.phone = this.generatePhone(opts.phone);
    }
    
    return account;
  }
  
  /**
   * 生成邮箱
   */
  private generateEmail(options: any = {}): string {
    const domain = options?.domain || this.getRandomItem(this.emailDomains);
    const prefix = this.generateEmailPrefix(options?.pattern);
    return `${prefix}@${domain}`;
  }
  
  /**
   * 生成邮箱前缀
   */
  private generateEmailPrefix(pattern?: string): string {
    if (pattern) {
      return pattern.replace('{random}', this.generateRandomString());
    }
    
    // 默认：8-12位随机字符串
    const length = this.randomInt(8, 12);
    return this.generateRandomString(length);
  }
  
  /**
   * 生成名字
   */
  private generateName(options: any = {}): { firstName: string; lastName: string; fullName: string } {
    const locale = options?.locale || 'en';
    
    if (locale === 'zh-CN') {
      const firstName = this.getRandomItem(this.chineseFirstNames);
      const lastName = this.getRandomItem(this.chineseLastNames);
      return {
        firstName,
        lastName,
        fullName: `${lastName}${firstName}`
      };
    }
    
    // 英文名字
    let firstNamePool: string[];
    const gender = options?.gender;
    
    if (gender === 'male') {
      firstNamePool = this.firstNames.male;
    } else if (gender === 'female') {
      firstNamePool = this.firstNames.female;
    } else {
      // 混合所有
      firstNamePool = [
        ...this.firstNames.male,
        ...this.firstNames.female,
        ...this.firstNames.neutral
      ];
    }
    
    const firstName = this.getRandomItem(firstNamePool);
    const lastName = this.getRandomItem(this.lastNames);
    
    return {
      firstName,
      lastName,
      fullName: `${firstName} ${lastName}`
    };
  }
  
  /**
   * 生成密码
   */
  private generatePassword(options: any = {}): string {
    const {
      length = 12,
      includeUppercase = true,
      includeLowercase = true,
      includeNumbers = true,
      includeSpecial = true,
      minUppercase = 1,
      minLowercase = 1,
      minNumbers = 1,
      minSpecial = 1
    } = options || {};
    
    let chars = '';
    let password = '';
    
    // 构建字符集
    if (includeLowercase) chars += this.lowercase;
    if (includeUppercase) chars += this.uppercase;
    if (includeNumbers) chars += this.numbers;
    if (includeSpecial) chars += this.special;
    
    // 确保满足最小要求
    if (includeLowercase && minLowercase > 0) {
      for (let i = 0; i < minLowercase; i++) {
        password += this.lowercase.charAt(this.randomInt(0, this.lowercase.length - 1));
      }
    }
    
    if (includeUppercase && minUppercase > 0) {
      for (let i = 0; i < minUppercase; i++) {
        password += this.uppercase.charAt(this.randomInt(0, this.uppercase.length - 1));
      }
    }
    
    if (includeNumbers && minNumbers > 0) {
      for (let i = 0; i < minNumbers; i++) {
        password += this.numbers.charAt(this.randomInt(0, this.numbers.length - 1));
      }
    }
    
    if (includeSpecial && minSpecial > 0) {
      for (let i = 0; i < minSpecial; i++) {
        password += this.special.charAt(this.randomInt(0, this.special.length - 1));
      }
    }
    
    // 填充剩余长度
    while (password.length < length) {
      password += chars.charAt(this.randomInt(0, chars.length - 1));
    }
    
    // 打乱顺序
    return this.shuffle(password);
  }
  
  /**
   * 生成用户名
   */
  private generateUsername(): string {
    const length = this.randomInt(8, 12);
    return this.generateRandomString(length);
  }
  
  /**
   * 生成手机号
   */
  private generatePhone(options: any = {}): string {
    // 美国格式：1 + 10位数字
    return `1${Math.floor(Math.random() * 9000000000 + 1000000000)}`;
  }
  
  /**
   * 生成随机字符串
   */
  private generateRandomString(length: number = 8): string {
    return Math.random().toString(36).substring(2, 2 + length);
  }
  
  /**
   * 打乱字符串
   */
  private shuffle(str: string): string {
    const arr = str.split('');
    for (let i = arr.length - 1; i > 0; i--) {
      const j = this.randomInt(0, i);
      [arr[i], arr[j]] = [arr[j], arr[i]];
    }
    return arr.join('');
  }
  
  /**
   * 生成随机整数
   */
  private randomInt(min: number, max: number): number {
    return Math.floor(Math.random() * (max - min + 1)) + min;
  }
  
  /**
   * 从数组中随机选择
   */
  private getRandomItem<T>(array: T[]): T {
    return array[this.randomInt(0, array.length - 1)];
  }
  
  /**
   * 批量生成（与旧框架一致）
   */
  async generateBatch(count: number, options: AccountGeneratorConfig = {}): Promise<AccountData[]> {
    const accounts: AccountData[] = [];
    for (let i = 0; i < count; i++) {
      accounts.push(await this.generate(options));
    }
    return accounts;
  }
}
