import fs from 'node:fs/promises'
import { globSync } from 'node:fs'
import path from 'node:path'
import { render } from './render.js'

export function stagesDir(file) {
  const basename = path.basename(file, path.extname(file))
  return path.join(path.dirname(file), `${basename}__stages`)
}

export async function processFile(file, { embedFonts = false } = {}) {
  const dir = stagesDir(file)

  const existingSvgs = await fs.readdir(dir).then(
    entries => entries.filter(e => e.endsWith('.svg')),
    () => []
  )
  if (existingSvgs.length > 0) {
    const [excalidrawStat, svgStat] = await Promise.all([
      fs.stat(file),
      fs.stat(path.join(dir, existingSvgs[0])),
    ])
    if (excalidrawStat.mtimeMs <= svgStat.mtimeMs) return 'up-to-date'
    await Promise.all(existingSvgs.map(svg => fs.unlink(path.join(dir, svg))))
  }

  const raw = await fs.readFile(file, 'utf8')
  const source = JSON.parse(raw)
  await fs.mkdir(dir, { recursive: true })
  await render(source, dir, { embedFonts })
  return 'built'
}

export async function processDir(dir, { embedFonts = false } = {}) {
  const files = globSync(`${dir}/*.excalidraw`)
  await Promise.all(files.map(f => processFile(f, { embedFonts })))
}
