import { cp, mkdir, readdir, rm } from "node:fs/promises"
import { existsSync } from "node:fs"
import { dirname, resolve } from "node:path"
import { fileURLToPath } from "node:url"

const here = dirname(fileURLToPath(import.meta.url))
const webRoot = resolve(here, "..")
const source = resolve(webRoot, "canvas-app", "dist")
const target = resolve(webRoot, "out")

if (!existsSync(source)) {
  throw new Error(`Canvas build output missing: ${source}`)
}

if (!existsSync(target)) {
  throw new Error(`Next export output missing: ${target}`)
}

await mkdir(target, { recursive: true })

for (const entry of await readdir(source)) {
  const from = resolve(source, entry)
  const to = resolve(target, entry)
  await rm(to, { recursive: true, force: true })
  await cp(from, to, { recursive: true, force: true })
}

await rm(resolve(target, "canvas"), { recursive: true, force: true })
