const fs = require('fs')
const path = require('path')

const root = path.join(__dirname, '..')
const distDir = path.join(root, 'dist')
const electronDir = path.join(root, 'electron')
const targetDistDir = path.join(electronDir, 'dist')

console.log('📦 Preparing Electron packaging...')

// 1. Verify dist directory exists
if (!fs.existsSync(distDir)) {
  console.error('❌ dist directory not found. Please run `npm run build` first.')
  process.exit(1)
}

// 2. Remove old dist directory in electron folder if exists
if (fs.existsSync(targetDistDir)) {
  console.log('🗑️  Removing old dist directory in electron folder...')
  fs.rmSync(targetDistDir, { recursive: true, force: true })
}

// 3. Copy dist directory to electron folder
console.log('📁 Copying dist directory to electron folder...')
copyRecursiveSync(distDir, targetDistDir)

console.log('✅ Electron packaging preparation complete!')

// Helper function to copy directories recursively
function copyRecursiveSync(src, dest) {
  const exists = fs.existsSync(src)
  const stats = exists && fs.statSync(src)
  const isDirectory = exists && stats.isDirectory()
  if (isDirectory) {
    if (!fs.existsSync(dest)) {
      fs.mkdirSync(dest, { recursive: true })
    }
    fs.readdirSync(src).forEach((childItemName) => {
      copyRecursiveSync(
        path.join(src, childItemName),
        path.join(dest, childItemName)
      )
    })
  } else {
    fs.copyFileSync(src, dest)
  }
}
