/**
 * Mention parsing for chat messages.
 *
 * Recognizes `@alias` tokens (case-insensitive, word-boundary) so the agent
 * can decide whether a group-chat message is directed at it.
 */

/** Escape regex metacharacters in an alias string. */
function escapeRegex(s: string): string {
  return s.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')
}

/**
 * Build a regex that matches `@<alias>` for any of the given aliases.
 * Requires a non-word char (or start) before `@` and a word boundary after the alias
 * so `@Claude` matches but `email@claudesomething` does not.
 */
function buildMentionRegex(aliases: string[]): RegExp | null {
  const cleaned = aliases.map(a => a.trim()).filter(a => a.length > 0)
  if (cleaned.length === 0) return null
  const alt = cleaned.map(escapeRegex).join('|')
  return new RegExp(`(?:^|[^\\w@])@(?:${alt})\\b`, 'i')
}

/** Returns true if `text` contains `@alias` for any alias (case-insensitive). */
export function containsMention(text: string, aliases: string[]): boolean {
  const re = buildMentionRegex(aliases)
  if (!re) return false
  return re.test(text)
}

/**
 * Remove `@alias` tokens from the text. Leaves surrounding whitespace tidy so
 * the cleaned prompt reads naturally (e.g. `"@Claude help"` → `"help"`).
 */
export function stripMention(text: string, aliases: string[]): string {
  const cleaned = aliases.map(a => a.trim()).filter(a => a.length > 0)
  if (cleaned.length === 0) return text
  const alt = cleaned.map(escapeRegex).join('|')
  const re = new RegExp(`(^|\\s)@(?:${alt})\\b[,:]?\\s*`, 'gi')
  return text.replace(re, (_m, lead) => (lead ? ' ' : '')).replace(/\s{2,}/g, ' ').trim()
}
