import * as monaco from 'monaco-editor'
import { setupMonacoEnvironment } from '@/monaco/setupMonacoEnv'
import {
  applyNexusEditorTheme,
  nexusEditorThemeId,
  registerNexusThemes,
  toggleNexusEditorTheme,
} from '@/monaco/nexusThemes'

let initialized = false

function registerNginxLanguage(): void {
  if (monaco.languages.getLanguages().some((l) => l.id === 'nginx')) return

  monaco.languages.register({ id: 'nginx', extensions: ['.conf'], aliases: ['Nginx', 'nginx'] })
  monaco.languages.setMonarchTokensProvider('nginx', {
    defaultToken: '',
    ignoreCase: true,
    tokenizer: {
      root: [
        [/\s+#.*$/, 'comment'],
        [/#.*$/, 'comment'],
        [
          /\b(server|listen|location|root|index|include|proxy_pass|proxy_set_header|fastcgi_pass|try_files|return|rewrite|if|set|limit_req|upstream|map|geo|ssl_certificate|access_log|error_log|gzip|types|default_type)\b/,
          'keyword',
        ],
        [/\$[a-zA-Z_][\w]*/, 'variable.predefined'],
        [/"[^"]*"/, 'string'],
        [/'[^']*'/, 'string'],
        [/\d+\.\d+\.\d+\.\d+/, 'number'],
        [/\d+[kmg]?\b/, 'number'],
        [/[{};]/, 'delimiter'],
      ],
    },
  })
}

export function initMonaco(): typeof monaco {
  if (!initialized) {
    setupMonacoEnvironment()
    registerNexusThemes(monaco)
    registerNginxLanguage()
    applyNexusEditorTheme(monaco)
    initialized = true
  }
  return monaco
}

export function buildMonacoEditorOptions(
  overrides?: monaco.editor.IStandaloneEditorConstructionOptions,
): monaco.editor.IStandaloneEditorConstructionOptions {
  return {
    theme: nexusEditorThemeId(),
    automaticLayout: true,
    lineNumbers: 'on',
    folding: true,
    bracketPairColorization: { enabled: true, independentColorPoolPerBracketType: true },
    matchBrackets: 'always',
    fontSize: 14,
    fontLigatures: true,
    fontFamily:
      "ui-monospace, SFMono-Regular, 'Cascadia Code', Menlo, Monaco, Consolas, 'Courier New', monospace",
    minimap: { enabled: true },
    tabSize: 4,
    insertSpaces: true,
    wordWrap: 'off',
    scrollBeyondLastLine: false,
    suggestOnTriggerCharacters: true,
    smoothScrolling: true,
    renderWhitespace: 'selection',
    colorDecorators: true,
    occurrencesHighlight: 'singleFile',
    selectionHighlight: true,
    renderLineHighlight: 'line',
    guides: {
      bracketPairs: true,
      bracketPairsHorizontal: true,
      indentation: true,
      highlightActiveIndentation: true,
    },
    ...overrides,
  }
}

export { monaco, applyNexusEditorTheme, toggleNexusEditorTheme }
