import type { LexerEntry } from './fetch-lexers'
import fs from 'node:fs'
import path from 'node:path'
import { capitalize, consola, fromRoot } from '@hugo-fixit/shared'
import { customCodeTypes } from './custom-types'

function escapeScssAlias(alias: string): string {
  // Match the old Tampermonkey script: replace . + : # with \\ + char
  return alias.replace(/([+.:#])/g, '\\\\$1')
}

export function generateScss(lexers: LexerEntry[]): void {
  const aliasMap = new Map<string, string>()

  for (const lexer of lexers) {
    for (const alias of lexer.aliases) {
      if (alias.includes(' ') || alias === '')
        continue
      const key = alias.toLowerCase()
      if (!aliasMap.has(key)) {
        aliasMap.set(key, capitalize(lexer.name))
      }
    }
  }

  const sorted = [...aliasMap.entries()].sort((a, b) =>
    a[0].localeCompare(b[0]),
  )

  const lines: string[] = [
    '/// Map of code identifiers/languages to Chroma supported languages.',
    '/// This file is auto-generated by `pnpm gen:lexers`, do not edit manually.',
    '/// @see https://github.com/hugo-fixit/FixIt/tree/main/packages/chroma-lexers',
    '$chroma-lexers: (',
  ]

  for (const [alias, name] of sorted) {
    lines.push(`  "${escapeScssAlias(alias)}": "${name}",`)
  }

  lines.push('  // Custom code type')

  const customEntries = Object.entries(customCodeTypes)
  for (let i = 0; i < customEntries.length; i++) {
    const [key, value] = customEntries[i]
    const comma = i < customEntries.length - 1 ? ',' : ''
    lines.push(`  "${key}": "${value}"${comma}`)
  }

  lines.push(') !default;')

  const outputPath = fromRoot('assets/scss/core/maps/_chroma-lexers.scss')
  fs.writeFileSync(outputPath, `${lines.join('\n')}\n`, 'utf-8')
  consola.success(`Written ${sorted.length + customEntries.length} entries to ${path.relative(fromRoot(), outputPath)}`)
}
