/**
 * 自然语言测试描述解析器
 * 将中文自然语言描述转换为测试代码
 */

class NaturalLanguageParser {
  constructor() {
    this.initializePatterns();
    this.initializeKeywords();
    this.initializeModuleMapping();
  }

  /**
   * 初始化识别模式
   */
  initializePatterns() {
    // 目标页面识别
    this.pagePatterns = [
      /目标页面[：:]\s*(.+)/,
      /在(.+?)页面/,
      /打开(.+?)页面/,
      /进入(.+?)页面/,
      /访问(.+?)页面/
    ];

    // 操作动作识别
    this.actionPatterns = [
      {
        pattern: /查询|搜索|检索/,
        action: 'search',
        description: '执行搜索操作'
      },
      {
        pattern: /点击|单击/,
        action: 'click',
        description: '点击元素'
      },
      {
        pattern: /输入|填写/,
        action: 'type',
        description: '输入文本'
      },
      {
        pattern: /查看|检查|验证/,
        action: 'verify',
        description: '验证元素'
      },
      {
        pattern: /选择|下拉选择/,
        action: 'select',
        description: '选择选项'
      },
      {
        pattern: /等待/,
        action: 'wait',
        description: '等待'
      }
    ];

    // 测试对象识别
    this.objectPatterns = [
      {
        pattern: /告警总览|告警页面/,
        module: '告警总览',
        selector: 'alerts'
      },
      {
        pattern: /首页|仪表盘|仪表板|主页/,
        module: '仪表盘',
        selector: 'dashboard'
      },
      {
        pattern: /布袋周期|布袋管理/,
        module: '布袋周期',
        selector: 'collector'
      },
      {
        pattern: /设备管理/,
        module: '设备管理',
        selector: 'equipment'
      },
      {
        pattern: /除尘器总览/,
        module: '除尘器总览',
        selector: 'dust'
      },
      {
        pattern: /除尘监测|监控/,
        module: '除尘监测',
        selector: 'dust-monitoring'
      },
      {
        pattern: /闭环管理/,
        module: '闭环管理',
        selector: 'my-loop'
      }
    ];

    // 数据类型识别
    this.dataPatterns = [
      {
        pattern: /告警数据|告警信息/,
        type: 'alert_data',
        selector: '.alert-data, [data-testid*="alert"]'
      },
      {
        pattern: /布袋健康度/,
        type: 'bag_health',
        selector: '[data-testid="dashboard-bag-progress"], .bag-health'
      },
      {
        pattern: /综合健康度/,
        type: 'overall_health',
        selector: '[data-testid="dashboard-health-score"], .health-score'
      },
      {
        pattern: /布袋总数/,
        type: 'bag_count',
        selector: '.bag-count, [data-testid*="bag-total"]'
      },
      {
        pattern: /顶部区域/,
        type: 'top_area',
        selector: '.top-area, .header-area, [data-testid*="header"]'
      }
    ];

    // 时间范围识别
    this.timePatterns = [
      {
        pattern: /今日|今天/,
        value: 'today',
        description: '今日数据'
      },
      {
        pattern: /昨日|昨天/,
        value: 'yesterday', 
        description: '昨日数据'
      },
      {
        pattern: /本周/,
        value: 'this_week',
        description: '本周数据'
      },
      {
        pattern: /本月/,
        value: 'this_month',
        description: '本月数据'
      }
    ];
  }

  /**
   * 初始化关键词映射
   */
  initializeKeywords() {
    this.keywords = {
      // 页面模块
      pages: {
        '首页': 'dashboard',
        '仪表盘': 'dashboard',
        '仪表板': 'dashboard',
        '主页': 'dashboard',
        '告警总览': 'alerts',
        '告警页面': 'alerts',
        '布袋周期': 'collectorList',
        '布袋管理': 'collectorList',
        '设备管理': 'management/device-management',
        '除尘器总览': 'dust-overview',
        '除尘监测': 'monitor',
        '监控页面': 'monitor',
        '闭环管理': 'my-loop'
      },
      
      // 操作动词
      actions: {
        '查询': 'search',
        '搜索': 'search',
        '检索': 'search',
        '查看': 'verify',
        '检查': 'verify',
        '验证': 'verify',
        '点击': 'click',
        '单击': 'click',
        '输入': 'type',
        '填写': 'type',
        '选择': 'select'
      }
    };
  }

  /**
   * 初始化模块映射
   */
  initializeModuleMapping() {
    this.moduleMapping = {
      '仪表盘': {
        route: 'dashboard',
        testId: 'dashboard',
        moduleName: '仪表盘'
      },
      '告警总览': {
        route: 'alerts',
        testId: 'alerts',
        moduleName: '告警总览'
      },
      '布袋周期': {
        route: 'collectorList',
        testId: 'collector',
        moduleName: '布袋周期'
      },
      '设备管理': {
        route: 'management/device-management',
        testId: 'equipment',
        moduleName: '设备管理'
      },
      '除尘器总览': {
        route: 'dust-overview',
        testId: 'dust',
        moduleName: '除尘器总览'
      },
      '除尘监测': {
        route: 'monitor',
        testId: 'dust-monitoring',
        moduleName: '除尘监测'
      },
      '闭环管理': {
        route: 'my-loop',
        testId: 'my-loop',
        moduleName: '闭环管理'
      }
    };
  }

  /**
   * 解析自然语言测试描述
   * @param {string} description - 自然语言描述
   * @returns {object} 解析后的测试结构
   */
  parseDescription(description) {
    const lines = description.split('\n').map(line => line.trim()).filter(line => line);
    
    let targetPage = '';
    let testSteps = [];
    let currentModule = '';

    // 解析每一行
    for (const line of lines) {
      // 识别目标页面
      if (this.isTargetPageLine(line)) {
        targetPage = this.extractTargetPage(line);
        currentModule = this.getModuleFromPage(targetPage);
        continue;
      }

      // 识别测试内容标题
      if (line.includes('测试内容')) {
        continue;
      }

      // 解析测试步骤
      if (this.isTestStepLine(line)) {
        const step = this.parseTestStep(line, currentModule);
        if (step) {
          testSteps.push(step);
        }
      }
    }

    return this.buildTestStructure(targetPage, testSteps);
  }

  /**
   * 判断是否为目标页面行
   */
  isTargetPageLine(line) {
    return this.pagePatterns.some(pattern => pattern.test(line));
  }

  /**
   * 提取目标页面
   */
  extractTargetPage(line) {
    for (const pattern of this.pagePatterns) {
      const match = line.match(pattern);
      if (match) {
        return match[1].trim();
      }
    }
    return '';
  }

  /**
   * 根据页面名称获取模块信息
   */
  getModuleFromPage(pageName) {
    return this.moduleMapping[pageName] || null;
  }

  /**
   * 判断是否为测试步骤行
   */
  isTestStepLine(line) {
    return /^\d+[.．,，]/.test(line) || line.includes('查询') || line.includes('查看');
  }

  /**
   * 解析单个测试步骤
   */
  parseTestStep(line, currentModule) {
    // 移除序号
    const cleanLine = line.replace(/^\d+[.．,，]\s*/, '');
    
    // 识别操作动作
    let action = 'verify'; // 默认为验证
    let actionDescription = '验证';
    
    for (const actionPattern of this.actionPatterns) {
      if (actionPattern.pattern.test(cleanLine)) {
        action = actionPattern.action;
        actionDescription = actionPattern.description;
        break;
      }
    }

    // 识别目标模块
    let targetModule = currentModule;
    for (const objPattern of this.objectPatterns) {
      if (objPattern.pattern.test(cleanLine)) {
        targetModule = this.moduleMapping[objPattern.module];
        break;
      }
    }

    // 识别数据类型和选择器
    let dataType = '';
    let selector = '';
    for (const dataPattern of this.dataPatterns) {
      if (dataPattern.pattern.test(cleanLine)) {
        dataType = dataPattern.type;
        selector = dataPattern.selector;
        break;
      }
    }

    // 识别时间范围
    let timeRange = '';
    for (const timePattern of this.timePatterns) {
      if (timePattern.pattern.test(cleanLine)) {
        timeRange = timePattern.value;
        break;
      }
    }

    return {
      originalText: cleanLine,
      action: action,
      actionDescription: actionDescription,
      module: targetModule,
      dataType: dataType,
      selector: selector,
      timeRange: timeRange,
      description: cleanLine
    };
  }

  /**
   * 构建测试结构
   */
  buildTestStructure(targetPage, testSteps) {
    const module = this.getModuleFromPage(targetPage);
    
    if (!module) {
      throw new Error(`未识别的页面: ${targetPage}`);
    }

    return {
      testSuite: {
        name: `${targetPage}功能测试`,
        module: module.moduleName,
        description: `基于自然语言描述生成的${targetPage}测试`,
        beforeEach: {
          login: true,
          visit: module.route,
          waitFor: [
            `[data-testid="${module.testId}-container"]`
          ]
        },
        scenarios: this.buildScenarios(testSteps, module)
      }
    };
  }

  /**
   * 构建测试场景
   */
  buildScenarios(testSteps, module) {
    const scenarios = [];
    
    for (let i = 0; i < testSteps.length; i++) {
      const step = testSteps[i];
      const scenario = {
        name: `应该能够${step.description}`,
        type: this.getTestType(step.action),
        description: step.originalText,
        priority: 'high',
        steps: this.buildSteps(step, module),
        expectedResults: this.buildExpectedResults(step, module)
      };
      
      scenarios.push(scenario);
    }

    return scenarios;
  }

  /**
   * 获取测试类型
   */
  getTestType(action) {
    const typeMapping = {
      'search': 'interaction',
      'click': 'interaction', 
      'type': 'interaction',
      'verify': 'ui',
      'select': 'interaction',
      'wait': 'data'
    };
    return typeMapping[action] || 'ui';
  }

  /**
   * 构建测试步骤
   */
  buildSteps(step, module) {
    const steps = [];

    // 如果需要切换模块
    if (step.module && step.module.route !== module.route) {
      steps.push({
        action: 'visit',
        target: `/#/${step.module.route}`,
        description: `访问${step.module.moduleName}页面`
      });
      
      steps.push({
        action: 'wait',
        value: 1000,
        description: '等待页面加载'
      });
    }

    // 添加具体操作步骤
    switch (step.action) {
      case 'search':
        if (step.timeRange) {
          steps.push({
            action: 'click',
            target: '[data-testid*="date-picker"], .el-date-editor',
            description: '打开日期选择器'
          });
          
          steps.push({
            action: 'custom',
            customCommand: `cy.selectTimeRange('${step.timeRange}')`,
            description: `选择${step.timeRange}时间范围`
          });
        }
        
        steps.push({
          action: 'click',
          target: '[data-testid*="search-button"], .search-btn',
          description: '执行搜索'
        });
        break;

      case 'verify':
        steps.push({
          action: 'verify',
          target: step.selector || `[data-testid*="${step.dataType}"]`,
          value: {
            assertion: 'be.visible'
          },
          description: step.description
        });
        break;

      case 'click':
        steps.push({
          action: 'click',
          target: step.selector,
          description: step.description
        });
        break;
    }

    return steps;
  }

  /**
   * 构建期望结果
   */
  buildExpectedResults(step, module) {
    const results = [];

    if (step.selector) {
      results.push({
        target: step.selector,
        assertion: 'be.visible'
      });
    }

    // 根据数据类型添加特定验证
    switch (step.dataType) {
      case 'alert_data':
        results.push({
          target: '.alert-list, [data-testid*="alert-table"]',
          assertion: 'be.visible'
        });
        break;
        
      case 'bag_health':
        results.push({
          target: '[data-testid="dashboard-bag-progress"]',
          assertion: 'be.visible'
        });
        break;
        
      case 'overall_health':
        results.push({
          target: '[data-testid="dashboard-health-score"]',
          assertion: 'be.visible'
        });
        break;
        
      case 'bag_count':
        results.push({
          target: '[data-testid*="bag-total"], .bag-count',
          assertion: 'be.visible'
        });
        break;
    }

    return results;
  }

  /**
   * 生成测试代码
   */
  generateTestCode(testStructure) {
    const TestCodeGenerator = require('./test-code-generator');
    const generator = new TestCodeGenerator();
    return generator.generateFromJSON(testStructure);
  }
}

module.exports = NaturalLanguageParser;