import { existsSync, mkdirSync, writeFileSync } from 'node:fs'
import { resolve, join } from 'node:path'
import { pathToFileURL } from 'node:url'

const CONFIG_FILES = ['deck.config.js', 'marp.config.mjs', 'marp.config.js']

function findUserConfig(root) {
  return CONFIG_FILES.map(f => resolve(root, f)).find(existsSync)
}

export function buildConfig(root) {
  const pluginFileUrl = import.meta.resolve('./marp-inline-svg.js')
  const userConfigPath = findUserConfig(root)

  let src
  if (userConfigPath) {
    const userConfigUrl = pathToFileURL(userConfigPath).href
    src = `import { inlineSvg } from ${JSON.stringify(pluginFileUrl)}
const { engine: userEngine, deck: _, ...userPrefs } = (await import(${JSON.stringify(userConfigUrl)})).default ?? {}
export default {
  ...userPrefs,
  html: true,
  engine: ({ marp }) => (userEngine ? userEngine({ marp }) : marp).use(inlineSvg),
}
`
  } else {
    src = `import { inlineSvg } from ${JSON.stringify(pluginFileUrl)}
export default {
  html: true,
  engine: ({ marp }) => marp.use(inlineSvg),
}
`
  }

  const tmpDir = join(root, 'tmp')
  mkdirSync(tmpDir, { recursive: true })

  const outPath = join(tmpDir, 'marp.config.mjs')
  writeFileSync(outPath, src)
  return outPath
}

export async function loadDeckMeta(root) {
  const userConfigPath = findUserConfig(root)
  if (!userConfigPath) return {}
  const config = (await import(pathToFileURL(userConfigPath).href)).default ?? {}
  return config.deck ?? {}
}
