import type { languages } from 'monaco-editor'

/**
 * Monarch tokenizer for ResolutionFlow tree markdown syntax.
 * Provides syntax highlighting for frontmatter, headings, options, references, and variables.
 */
export const resolutionFlowLanguage: languages.IMonarchLanguage = {
  tokenizer: {
    root: [
      // Frontmatter delimiter
      [/^---\s*$/, 'delimiter.frontmatter', '@frontmatter'],

      // Headings
      [/^##\s+.*$/, 'heading.action'],
      [/^#\s+.*$/, 'heading.decision'],

      // Blockquote (help text)
      [/^>\s.*$/, 'string.blockquote'],

      // Option lines: - [X] Label → @target_id
      [/^-\s*\[[A-Za-z0-9]+\]/, 'keyword.option', '@optionLine'],

      // Next node reference: → @node_id
      [/^→\s*@\S+/, 'variable.reference'],

      // Expected outcome
      [/^\*\*Expected:\*\*\s*.*$/, 'keyword.expected'],

      // Command block
      [/^```commands\s*$/, 'delimiter.commands', '@commandBlock'],
      [/^```\s*$/, 'delimiter.commands'],

      // Variable tokens
      [/\[USER_INPUT:[^\]]+\]/, 'variable.input'],
      [/\[VAR:[^\]]+\]/, 'variable.reference'],
      [/\[SAVE_AS:[^\]]+\]/, 'variable.save'],

      // Ordered list items
      [/^\d+\.\s+/, 'keyword.step'],

      // Bold
      [/\*\*[^*]+\*\*/, 'strong'],

      // Inline code
      [/`[^`]+`/, 'string.code'],

      // Regular text
      [/./, 'text'],
    ],

    frontmatter: [
      [/^---\s*$/, 'delimiter.frontmatter', '@pop'],
      [/^(id)(:)(.*)$/, ['keyword.frontmatter', 'delimiter', 'string.id']],
      [/^(type)(:)(.*)$/, ['keyword.frontmatter', 'delimiter', 'type.value']],
      [/^(parent)(:)(.*)$/, ['keyword.frontmatter', 'delimiter', 'string.parent']],
      [/./, 'variable.other'],
    ],

    optionLine: [
      [/→\s*@\S+/, 'variable.reference'],
      [/$/, '', '@pop'],
      [/./, 'string.option'],
    ],

    commandBlock: [
      [/^```\s*$/, 'delimiter.commands', '@pop'],
      [/./, 'string.command'],
    ],
  },
}

export const LANGUAGE_ID = 'resolutionflow'
