/**
 * Lightweight IR (Intermediate Representation) parser for mentions.
 * 
 * Syntax: @[type:id:label]
 * - @[user:abc123:John] — user mention
 * - @[repo:xyz789:my-repo] — repository mention
 * - @[issue:def456:Bug #42] — issue mention
 * - @[pr:ghi012:PR Fix header] — pull request mention
 * - @[room:jkl345:general] — room/channel mention
 */

export interface MentionData {
  entityType: string;
  entityId: string;
  entityLabel: string;
}

const MENTION_RE = /@\[([a-z_]+):([^:\]]+):([^\]]+)\]/g;

export interface ParsedSegment {
  type: 'text' | 'mention';
  content: string;
  mention?: MentionData;
}

/** Parse content string into text and mention segments. */
export function parseMentions(content: string): ParsedSegment[] {
  if (!content) return [];
  
  const segments: ParsedSegment[] = [];
  let lastIndex = 0;
  let match: RegExpExecArray | null;

  // Reset regex state
  MENTION_RE.lastIndex = 0;

  while ((match = MENTION_RE.exec(content)) !== null) {
    // Text before mention
    if (match.index > lastIndex) {
      segments.push({
        type: 'text',
        content: content.slice(lastIndex, match.index),
      });
    }
    // Mention
    segments.push({
      type: 'mention',
      content: match[0],
      mention: {
        entityType: match[1],
        entityId: match[2],
        entityLabel: match[3],
      },
    });
    lastIndex = match.index + match[0].length;
  }

  // Remaining text
  if (lastIndex < content.length) {
    segments.push({
      type: 'text',
      content: content.slice(lastIndex),
    });
  }

  if (segments.length === 0) {
    segments.push({ type: 'text', content });
  }

  return segments;
}

/**
 * Format a mention string from entity data.
 * For use when inserting a mention into the composer input.
 */
export function formatMention(entityType: string, entityId: string, entityLabel: string): string {
  return `@[${entityType}:${entityId}:${entityLabel}]`;
}

/** Check if a string contains any mentions. */
export function hasMentions(content: string): boolean {
  MENTION_RE.lastIndex = 0;
  return MENTION_RE.test(content);
}

/** Extract all mention data from content. */
export function extractMentions(content: string): MentionData[] {
  const mentions: MentionData[] = [];
  MENTION_RE.lastIndex = 0;
  let match: RegExpExecArray | null;
  while ((match = MENTION_RE.exec(content)) !== null) {
    mentions.push({
      entityType: match[1],
      entityId: match[2],
      entityLabel: match[3],
    });
  }
  return mentions;
}
