/**
 * Shared query-tokenization / excerpt helpers for the conversation-search
 * tools (SearchTaskConversation / SearchWorkspaceTasks).
 *
 * Extracted into one module so the semantics cannot drift between the two
 * tools again — the "whole query as one literal substring" bug lived in two
 * independent copies of this code.
 */

/** Collapse all whitespace runs into single spaces. */
export function collapse(s: string): string {
  return s.replace(/\s+/g, ' ').trim();
}

/** Lowercase AND tokens split on any whitespace (incl. full-width U+3000). */
export function tokenize(query: string): string[] {
  return query.toLowerCase().split(/\s+/).filter(Boolean);
}

/** Compact excerpt centered on the earliest token hit, bounded to `max` chars. */
export function excerpt(body: string, tokens: string[], max: number): string {
  const flat = collapse(body);
  if (flat.length <= max) return flat;
  const lower = flat.toLowerCase();
  let idx = -1;
  for (const t of tokens) {
    const i = lower.indexOf(t);
    if (i >= 0 && (idx < 0 || i < idx)) idx = i;
  }
  if (idx < 0) return flat.slice(0, max - 1) + '…';
  const start = Math.max(0, idx - 40);
  const end = Math.min(flat.length, start + max);
  return (start > 0 ? '…' : '') + flat.slice(start, end) + (end < flat.length ? '…' : '');
}
