function normalizeSpace(value) {
  return String(value ?? "").replace(/\s+/g, " ").trim();
}

const SEARCH_QUERY_NOISE_PATTERN = /^(待确认|未知|通用|暂无|无|空|n\/?a|na|none|null)$/i;

function dedupeList(values) {
  const seen = new Set();
  const output = [];

  for (const value of values) {
    const normalized = normalizeSpace(value).toLowerCase();
    if (!normalized || seen.has(normalized)) {
      continue;
    }

    seen.add(normalized);
    output.push(normalizeSpace(value));
  }

  return output;
}

export function buildSearchQueryVariants(query, options = {}) {
  const normalizedQuery = normalizeSpace(query);
  if (!normalizedQuery) {
    return [];
  }

  if (options.strict === true) {
    return [normalizedQuery];
  }

  const tokens = dedupeList(normalizedQuery.split(/\s+/).map((item) => normalizeSpace(item)).filter(Boolean));
  const variants = [];
  const pushVariant = (value) => {
    const normalized = normalizeSpace(value);
    if (!normalized || variants.includes(normalized)) {
      return;
    }

    variants.push(normalized);
  };

  pushVariant(normalizedQuery);

  const cleanedTokens = tokens.filter((token) => !SEARCH_QUERY_NOISE_PATTERN.test(token));
  pushVariant(cleanedTokens.join(" "));

  if (cleanedTokens.length >= 2) {
    pushVariant(cleanedTokens.slice(0, 2).join(" "));
  }

  if (cleanedTokens.length >= 1) {
    pushVariant(cleanedTokens[0]);
  }

  return variants.length > 0 ? variants : [normalizedQuery];
}