/*
*  author: Yagnik Poshiya
*  organization: Webbrains Technologies Private Limited
*/

/**
 * A very small Markdown tokeniser for the storage editor's highlight overlay.
 *
 * Deliberately line-based. The editor does not wrap lines, so one source line
 * is one visual row, which is what keeps the gutter's line numbers aligned with
 * the text. A block-level parser that merged lines would break that.
 *
 * This exists to make Markdown *readable while editing* — it is not a renderer
 * and does not need to agree with any particular Markdown flavour.
 */

export type MarkdownTokenKind =
  | 'plain'
  | 'heading'
  | 'fence'
  | 'code'
  | 'quote'
  | 'marker'
  | 'bold'
  | 'italic'
  | 'linkText'
  | 'linkUrl'
  | 'hr';

export type MarkdownToken = { text: string; kind: MarkdownTokenKind };
export type MarkdownLine = { tokens: MarkdownToken[] };

const INLINE = /(`[^`\n]*`)|(\*\*[^*\n]+\*\*)|(__[^_\n]+__)|(\*[^*\n]+\*)|(_[^_\n]+_)|(\[[^\]\n]*\]\([^)\n]*\))/g;

function pushPlain(tokens: MarkdownToken[], text: string): void {
  if (text) tokens.push({ text, kind: 'plain' });
}

function tokenizeInline(line: string): MarkdownToken[] {
  const tokens: MarkdownToken[] = [];
  let lastIndex = 0;

  INLINE.lastIndex = 0;
  let match: RegExpExecArray | null = INLINE.exec(line);
  while (match) {
    pushPlain(tokens, line.slice(lastIndex, match.index));
    const value = match[0];

    if (value.startsWith('`')) {
      tokens.push({ text: value, kind: 'code' });
    } else if (value.startsWith('**') || value.startsWith('__')) {
      tokens.push({ text: value, kind: 'bold' });
    } else if (value.startsWith('[')) {
      const split = value.indexOf('](');
      tokens.push({ text: value.slice(0, split + 1), kind: 'linkText' });
      tokens.push({ text: value.slice(split + 1), kind: 'linkUrl' });
    } else {
      tokens.push({ text: value, kind: 'italic' });
    }

    lastIndex = match.index + value.length;
    match = INLINE.exec(line);
  }

  pushPlain(tokens, line.slice(lastIndex));
  return tokens.length > 0 ? tokens : [{ text: '', kind: 'plain' }];
}

export function tokenizeMarkdown(text: string): MarkdownLine[] {
  const lines = String(text ?? '').split('\n');
  const out: MarkdownLine[] = [];
  let insideFence = false;

  for (const line of lines) {
    // A fence toggles the block, and the fence line itself is not code.
    if (/^\s*(```|~~~)/.test(line)) {
      insideFence = !insideFence;
      out.push({ tokens: [{ text: line, kind: 'fence' }] });
      continue;
    }

    if (insideFence) {
      out.push({ tokens: [{ text: line, kind: 'code' }] });
      continue;
    }

    if (/^\s{0,3}#{1,6}\s/.test(line)) {
      out.push({ tokens: [{ text: line, kind: 'heading' }] });
      continue;
    }

    if (/^\s{0,3}([-*_])\s*(\1\s*){2,}$/.test(line)) {
      out.push({ tokens: [{ text: line, kind: 'hr' }] });
      continue;
    }

    if (/^\s*>/.test(line)) {
      out.push({ tokens: [{ text: line, kind: 'quote' }] });
      continue;
    }

    const listMatch = /^(\s*)([-*+]|\d+[.)])(\s+)/.exec(line);
    if (listMatch) {
      const [, indent, marker, gap] = listMatch;
      const rest = line.slice(listMatch[0].length);
      out.push({
        tokens: [
          ...(indent ? [{ text: indent, kind: 'plain' as const }] : []),
          { text: marker, kind: 'marker' },
          { text: gap, kind: 'plain' },
          ...tokenizeInline(rest),
        ],
      });
      continue;
    }

    out.push({ tokens: tokenizeInline(line) });
  }

  return out;
}

/** Plain text still needs one token per line so the overlay rows line up. */
export function tokenizePlainText(text: string): MarkdownLine[] {
  return String(text ?? '')
    .split('\n')
    .map((line) => ({ tokens: [{ text: line, kind: 'plain' as const }] }));
}

export function tokenizeForExtension(text: string, extension: string): MarkdownLine[] {
  const ext = String(extension ?? '').trim().toLowerCase().replace(/^\./, '');
  return ext === 'md' ? tokenizeMarkdown(text) : tokenizePlainText(text);
}
