import type { languages, editor, Position, IRange } from 'monaco-editor'

interface NodeInfo {
  id: string
  label: string
  type: string
}

/**
 * Create a completion provider for ResolutionFlow markdown.
 * Provides autocomplete for node references, types, and templates.
 */
export function createCompletionProvider(
  getNodes: () => NodeInfo[]
): languages.CompletionItemProvider {
  return {
    triggerCharacters: ['@', ':', '['],
    provideCompletionItems(
      model: editor.ITextModel,
      position: Position,
    ): languages.ProviderResult<languages.CompletionList> {
      const lineContent = model.getLineContent(position.lineNumber)
      const textUntilPosition = lineContent.substring(0, position.column - 1)

      const word = model.getWordUntilPosition(position)
      const range: IRange = {
        startLineNumber: position.lineNumber,
        endLineNumber: position.lineNumber,
        startColumn: word.startColumn,
        endColumn: word.endColumn,
      }

      const suggestions: languages.CompletionItem[] = []

      // After @ — suggest node IDs
      if (textUntilPosition.endsWith('@') || textUntilPosition.match(/@\w*$/)) {
        const atPos = textUntilPosition.lastIndexOf('@')
        const atRange: IRange = {
          startLineNumber: position.lineNumber,
          endLineNumber: position.lineNumber,
          startColumn: atPos + 2, // after the @
          endColumn: position.column,
        }

        const nodes = getNodes()
        for (const node of nodes) {
          const typeIcon = node.type === 'decision' ? '?' : node.type === 'action' ? '!' : '='
          suggestions.push({
            label: `${node.id} — ${node.label}`,
            kind: 18, // CompletionItemKind.Reference
            insertText: node.id,
            detail: `${typeIcon} ${node.type}`,
            range: atRange,
          })
        }
        return { suggestions }
      }

      // After "type:" — suggest node types
      if (textUntilPosition.match(/^type:\s*$/)) {
        for (const t of ['decision', 'action', 'solution']) {
          suggestions.push({
            label: t,
            kind: 12, // CompletionItemKind.Value
            insertText: t,
            range,
          })
        }
        return { suggestions }
      }

      // After "---\n" at beginning — suggest node template
      if (lineContent.trim() === '---' && position.lineNumber <= 2) {
        suggestions.push(
          {
            label: 'Decision Node',
            kind: 14, // CompletionItemKind.Snippet
            insertText: [
              '',
              'id: ${1:node_id}',
              'type: decision',
              '---',
              '# ${2:What is the question?}',
              '',
              '> ${3:Help text for the engineer}',
              '',
              '- [A] ${4:Option A} → @${5:target_id}',
              '- [B] ${6:Option B} → @${7:target_id}',
            ].join('\n'),
            insertTextRules: 4, // InsertTextRule.InsertAsSnippet
            detail: 'Decision node template',
            range,
          },
          {
            label: 'Action Node',
            kind: 14,
            insertText: [
              '',
              'id: ${1:node_id}',
              'type: action',
              'parent: ${2:parent_id}',
              '---',
              '## ${3:Action Title}',
              '',
              '${4:Description of what to do}',
              '',
              '```commands',
              '${5:command here}',
              '```',
              '',
              '**Expected:** ${6:Expected outcome}',
              '',
              '→ @${7:next_node_id}',
            ].join('\n'),
            insertTextRules: 4,
            detail: 'Action node template',
            range,
          },
          {
            label: 'Solution Node',
            kind: 14,
            insertText: [
              '',
              'id: ${1:node_id}',
              'type: solution',
              'parent: ${2:parent_id}',
              '---',
              '## ${3:Solution Title}',
              '',
              '${4:Description}',
              '',
              '1. ${5:Step 1}',
              '2. ${6:Step 2}',
            ].join('\n'),
            insertTextRules: 4,
            detail: 'Solution node template',
            range,
          },
        )
        return { suggestions }
      }

      // After [VAR: — suggest variable names
      if (textUntilPosition.match(/\[VAR:$/)) {
        // Could be extended to track variable names from the document
        suggestions.push(
          { label: 'hostname', kind: 5, insertText: 'hostname', range },
          { label: 'username', kind: 5, insertText: 'username', range },
          { label: 'ticket_number', kind: 5, insertText: 'ticket_number', range },
          { label: 'client_name', kind: 5, insertText: 'client_name', range },
        )
        return { suggestions }
      }

      return { suggestions }
    },
  }
}
