/**
 * Automation Framework Tool - 基于配置的自动化注册工具
 */

const fs = require('fs');
const path = require('path');
const logger = require('../../shared/logger');
const BrowserManager = require('../../shared/libs/browser/browser-manager');

const TOOL_NAME = 'automation-framework';

class AutomationFramework {
  constructor() {
    this.sites = new Map();
    this.loadSites();
  }

  /**
   * 加载所有站点适配器
   */
  loadSites() {
    const sitesDir = path.join(__dirname, 'sites');
    
    try {
      const files = fs.readdirSync(sitesDir);
      
      files.forEach(file => {
        if (file.endsWith('-adapter.js')) {
          const siteName = file.replace('-adapter.js', '');
          try {
            const AdapterClass = require(path.join(sitesDir, file));
            this.sites.set(siteName, AdapterClass);
            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, profileId } = options;

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

      if (!profileId) {
        logger.error(TOOL_NAME, '请指定 AdsPower Profile ID');
        process.exit(1);
      }

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

      logger.info(TOOL_NAME, `========================================`);
      logger.info(TOOL_NAME, `开始 ${site} 注册流程`);
      logger.info(TOOL_NAME, `AdsPower Profile: ${profileId}`);
      logger.info(TOOL_NAME, `========================================`);
      
      // 启动浏览器
      const browserManager = new BrowserManager({
        profileId: profileId,
        siteName: TOOL_NAME
      });
      
      await browserManager.launch();
      
      const browser = browserManager.browser;
      const page = browserManager.page;
      
      // 创建上下文
      const context = {
        page,
        browser,
        logger,
        data: {},
        profileId,
        validateConfig: options.validateConfig !== false,
        performanceReport: options.performanceReport !== false
      };
      
      // 创建适配器并执行
      const adapter = new AdapterClass(context);
      const result = await adapter.execute();
      
      // 关闭浏览器
      await browserManager.close();
      
      if (result.success) {
        logger.success(TOOL_NAME, '注册流程完成');
        
        // 保存结果
        if (options.output) {
          const outputData = {
            site,
            account: context.data.account,
            card: context.data.card,
            subscription: context.data.subscription,
            timestamp: new Date().toISOString()
          };
          
          fs.writeFileSync(
            options.output,
            JSON.stringify(outputData, null, 2)
          );
          logger.success(TOOL_NAME, `结果已保存到: ${options.output}`);
        }
      }
      
      // 返回兼容格式
      return {
        success: result.success,
        siteName: site,
        accountData: context.data.account,
        cardInfo: context.data.card,
        subscription: context.data.subscription,
        result,
        performance: result.performance
      };

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

  /**
   * 列出支持的网站
   */
  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('');
  }

  /**
   * 验证配置文件
   */
  validateConfig(siteName) {
    const ConfigValidator = require('./core/config-validator');
    const yaml = require('js-yaml');
    
    try {
      const configPath = path.join(__dirname, 'configs/sites', `${siteName}.yaml`);
      
      if (!fs.existsSync(configPath)) {
        logger.error(TOOL_NAME, `配置文件不存在: ${siteName}.yaml`);
        return;
      }
      
      const configContent = fs.readFileSync(configPath, 'utf8');
      const config = yaml.load(configContent);
      
      const validator = new ConfigValidator();
      const result = validator.validate(config);
      
      if (result.valid) {
        logger.success(TOOL_NAME, `✓ 配置验证通过: ${siteName}`);
        logger.info(TOOL_NAME, `  - 步骤数: ${config.workflow.length}`);
      } else {
        logger.error(TOOL_NAME, `✗ 配置验证失败: ${siteName}`);
        result.errors.forEach(err => {
          logger.error(TOOL_NAME, `  - ${err}`);
        });
      }
      
    } catch (error) {
      logger.error(TOOL_NAME, `验证失败: ${error.message}`);
    }
  }
}

/**
 * 兼容旧接口：静态方法
 */
class AutomationFactory {
  /**
   * 使用 AdsPower 注册（兼容旧接口）
   */
  static async registerWithAdsPower(siteName, profileId, options = {}) {
    const tool = new AutomationFramework();
    return await tool.execute({
      site: siteName,
      profileId: profileId,
      ...options
    });
  }
}

module.exports = {
  name: TOOL_NAME,
  alias: 'auto',
  description: '基于配置的自动化注册工具（新框架）',
  execute: async (options) => {
    const tool = new AutomationFramework();
    await tool.execute(options);
  },
  listSites: () => {
    const tool = new AutomationFramework();
    tool.listSites();
  },
  validateConfig: (siteName) => {
    const tool = new AutomationFramework();
    tool.validateConfig(siteName);
  },
  // 导出类以支持旧接口
  AutomationFactory,
  // 兼容旧的直接调用方式
  registerWithAdsPower: AutomationFactory.registerWithAdsPower
};
