import Markdoc, { type Config } from '@markdoc/markdoc'
import { ensureShikiEngine, shikiRender } from './markdown'

const { nodes, Tag } = Markdoc

export const markdocConfig: Config = {
  nodes: {
    fence: {
      render: 'CodeBlock',
      attributes: {
        ...nodes.fence.attributes,
        highlightedHtml: { type: String },
      },
      transform(node, config) {
        const attributes = node.transformAttributes(config)

        const highlightedHtml = shikiRender(
          node.attributes.content,
          node.attributes.language,
        )

        return new Tag(
          'CodeBlock',
          { ...attributes, highlightedHtml },
          node.transformChildren(config),
        )
      },
    },
  },
}

export const toMarkdocTree = async (content: string) => {
  const ast = Markdoc.parse(content)
  await ensureShikiEngine()
  return Markdoc.transform(ast, markdocConfig)
}
