import type { Item, ElementGroup } from './types';

/**
 * 从元素库分组中构建操作数名集合（用于词法解析时识别操作数）
 */
export function buildOperandSet(elementGroups: ElementGroup[]): Set<string> {
  const set = new Set<string>();
  elementGroups.forEach((group) => {
    if (group.type === 'operand') group.items.forEach((item) => set.add(item.value));
  });
  return set;
}

/**
 * 将表达式字符串解析为 Item 数组（词法分析）
 *
 * 识别：操作数（变量名）、比较/算术运算符、逻辑运算符、括号、数字
 */
export function parseExpression(str: string, operandSet: Set<string>): Item[] {
  if (!str?.trim()) return [];

  const operandPattern = [...operandSet]
    .sort((a, b) => b.length - a.length) // 长名优先，避免 "temperature" 吃掉 "temperatureDifferenceOut"
    .map((v) => v.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'))
    .join('|');
  const regex = new RegExp(`(${operandPattern}|==|>=|<=|&&|\\|\\||-?\\d+(?:\\.\\d+)?|[>+\\-*/<()])`, 'g');
  const rawTokens = str.match(regex);

  if (!rawTokens) return [];

  const items: Item[] = [];

  for (const token of rawTokens) {
    if (token === '(') {
      items.push({ type: 'leftParen', value: token });
      continue;
    }
    if (token === ')') {
      items.push({ type: 'rightParen', value: token });
      continue;
    }
    if (token === '&&' || token === '||') {
      items.push({ type: 'logic', value: token });
      continue;
    }
    if (['>', '>=', '<', '<=', '==', '+', '-', '*', '/'].includes(token)) {
      items.push({ type: 'operator', value: token });
      continue;
    }
    if (operandSet.has(token)) {
      items.push({ type: 'operand', value: token });
      continue;
    }
    if (/^-?\d+(?:\.\d+)?$/.test(token)) {
      items.push({ type: 'number', value: token });
      continue;
    }
  }

  return items;
}

/**
 * 将 Item 格式化为可读的展示文本
 */
export function formatDisplay(item: Item, displayMap: Record<string, string>): string {
  if (item.type === 'number') return item.value;
  return displayMap[item.value] || item.value;
}
