import fs from 'node:fs'
import path from 'node:path'
import { fileURLToPath } from 'node:url'

const root = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..')
const publicDir = path.join(root, '.vitepress', 'public')

function copyDir(source, target) {
  if (!fs.existsSync(source)) return
  fs.mkdirSync(target, { recursive: true })

  for (const entry of fs.readdirSync(source, { withFileTypes: true })) {
    const from = path.join(source, entry.name)
    const to = path.join(target, entry.name)
    if (entry.isDirectory()) {
      copyDir(from, to)
    } else {
      fs.copyFileSync(from, to)
    }
  }
}

function resetPublicDir() {
  if (fs.existsSync(publicDir)) {
    fs.rmSync(publicDir, { recursive: true, force: true })
  }
  fs.mkdirSync(publicDir, { recursive: true })
}

resetPublicDir()
copyDir(path.join(root, 'assets'), path.join(publicDir, 'assets'))
copyDir(path.join(root, 'images'), path.join(publicDir, 'images'))

console.log('[prepare-public] assets 与 images 已同步到 .vitepress/public')
