/**
 * Account Register Tool - 账号注册工具入口
 */

const fs = require('fs');
const path = require('path');
const AccountDataGenerator = require('../../shared/libs/account-generator');
const logger = require('../../shared/logger');
const { OUTPUT_FORMATS } = require('./config');

const TOOL_NAME = 'account-register';

class AccountRegister {
  constructor() {
    this.sites = new Map();
    this.dataGen = new AccountDataGenerator();
    this.loadSites();
  }

  /**
   * 加载所有网站脚本
   */
  loadSites() {
    const sitesDir = path.join(__dirname, 'sites');
    
    try {
      const files = fs.readdirSync(sitesDir);
      
      files.forEach(file => {
        if (file.endsWith('.js')) {
          const siteName = file.replace('.js', '');
          try {
            const SiteClass = require(path.join(sitesDir, file));
            this.sites.set(siteName, SiteClass);
            logger.debug(TOOL_NAME, `Loaded site: ${siteName}`);
          } catch (error) {
            logger.warn(TOOL_NAME, `Failed to load site ${siteName}: ${error.message}`);
          }
        }
      });
    } catch (error) {
      logger.warn(TOOL_NAME, `Failed to load sites: ${error.message}`);
    }
  }

  /**
   * 执行注册
   */
  async execute(options) {
    const { site, dryRun, format } = options;

    try {
      if (!site) {
        logger.error(TOOL_NAME, '请指定网站名称');
        this.listSites();
        process.exit(1);
      }

      const SiteClass = this.sites.get(site);
      if (!SiteClass) {
        logger.error(TOOL_NAME, `未知的网站: ${site}`);
        this.listSites();
        process.exit(1);
      }

      const siteInstance = new SiteClass();

      if (dryRun) {
        // 干运行模式：只生成数据
        logger.info(TOOL_NAME, '干运行模式：只生成账号数据');
        const account = siteInstance.generateData(options);
        
        const formatter = OUTPUT_FORMATS[format || 'simple'];
        console.log('\n' + formatter.formatter(account) + '\n');
        
        logger.success(TOOL_NAME, '账号数据生成完成');
      } else {
        // 真正执行注册
        logger.info(TOOL_NAME, `开始注册 ${site} 账号...`);
        const result = await siteInstance.register(options);
        
        if (result.success) {
          logger.success(TOOL_NAME, '注册流程完成');
          
          if (options.output) {
            // 保存到文件
            fs.writeFileSync(
              options.output,
              JSON.stringify(result.account, null, 2)
            );
            logger.success(TOOL_NAME, `账号数据已保存到: ${options.output}`);
          }
        }
      }

    } catch (error) {
      logger.error(TOOL_NAME, error.message);
      process.exit(1);
    }
  }

  /**
   * 只生成数据（不执行注册）
   */
  generate(options) {
    logger.info(TOOL_NAME, '生成账号数据...');
    
    const account = this.dataGen.generateAccount({
      name: options.name,
      email: options.email,
      username: options.username,
      password: options.password,
      phone: options.phone,
      includeCard: options.includeCard
    });

    const formatter = OUTPUT_FORMATS[options.format || 'simple'];
    console.log('\n' + formatter.formatter(account) + '\n');
  }

  /**
   * 列出支持的网站
   */
  listSites() {
    const sites = Array.from(this.sites.keys());
    
    if (sites.length === 0) {
      console.log('\n暂无可用网站\n');
      return;
    }

    console.log('\n支持的网站:\n');
    sites.forEach(site => {
      console.log(`  ${site}`);
    });
    console.log('');
  }

  /**
   * 列出支持的格式
   */
  listFormats() {
    console.log('\n支持的输出格式:\n');
    for (const [key, config] of Object.entries(OUTPUT_FORMATS)) {
      console.log(`  ${key.padEnd(15)} - ${config.name}`);
    }
    console.log('');
  }
}

module.exports = {
  name: TOOL_NAME,
  alias: 'register',
  description: '自动注册账号',
  execute: async (options) => {
    const tool = new AccountRegister();
    await tool.execute(options);
  },
  listSites: () => {
    const tool = new AccountRegister();
    tool.listSites();
  },
  listFormats: () => {
    const tool = new AccountRegister();
    tool.listFormats();
  },
  generate: (options) => {
    const tool = new AccountRegister();
    tool.generate(options);
  }
};
