import type { LanguageInput, ThemedToken, ThemeInput } from 'shiki'
import type { TokenType } from '../../types'
import { createHighlighterCore } from 'vendor/shiki/core/core'
import { createJavaScriptRegexEngine } from 'vendor/shiki/core/engine-javascript'

async function initializeHighlighter(langs: LanguageInput[], themes: ThemeInput[]): Promise<Awaited<ReturnType<typeof createHighlighterCore>>> {
  return createHighlighterCore({
    engine: createJavaScriptRegexEngine(),
    langs,
    themes,
  })
}

export async function createHighlighter({ langs, themes }: { langs: LanguageInput[], themes: ThemeInput[] }): Promise<Awaited<ReturnType<typeof createHighlighterCore>>> {
  if (!langs?.length || !themes?.length) {
    throw new Error('Please provide both `langs` and `themes` when creating a highlighter.')
  }

  try {
    const highlighter = await initializeHighlighter(langs, themes)
    console.log('Initialized highlighter:', highlighter)
    return highlighter
  }
  catch (error) {
    console.error('Failed to create highlighter:', error)
    throw error
  }
}

export function processTokens(tokens: ThemedToken[]): TokenType[] {
  return tokens.map(token => ({
    content: token.content,
    color: token.color || '#000000',
    fontStyle: token.fontStyle?.toString(),
  }))
}
