const LEFT_BOUNDARY_CHARS = new Set(['(', '[', '{', '"', "'", ',', ':', ';', '!', '?']);

function isWhitespaceChar(char) {
  return char === ' ' || char === '\t' || char === '\n' || char === '\r';
}

function isInlineSkillLeftBoundary(char) {
  return char === undefined || isWhitespaceChar(char) || LEFT_BOUNDARY_CHARS.has(char);
}

export function extractInlineSkillAutocompleteToken(textBeforeCursor) {
  const slashIndex = textBeforeCursor.lastIndexOf('/');
  if (slashIndex === -1) return null;
  if (!isInlineSkillLeftBoundary(textBeforeCursor[slashIndex - 1])) return null;

  const token = textBeforeCursor.slice(slashIndex);
  if (token.includes('/', 1) || token.includes(' ')) return null;

  if (token === '/') {
    return { token, query: '', explicit: false };
  }

  if (token.startsWith('/skill:')) {
    const query = token.slice('/skill:'.length);
    return /^[a-z0-9-]*$/.test(query) ? { token, query, explicit: true } : null;
  }

  const query = token.slice(1);
  return /^[a-z0-9-]*$/.test(query) ? { token, query, explicit: false } : null;
}
