const { execSync } = require('child_process')
const fs = require('fs')
const path = require('path')
const AdmZip = require('adm-zip')

const root = path.join(__dirname, '..')
const dist = path.join(root, 'dist')
const release = path.join(root, 'release')
const jsonPath = path.join(root, 'public', 'scenes', 'demo.json')

// 1. Verify JSON exists and is valid
if (!fs.existsSync(jsonPath)) {
  console.error('❌ public/scenes/demo.json not found')
  process.exit(1)
}

try {
  JSON.parse(fs.readFileSync(jsonPath, 'utf-8'))
  console.log('✅ JSON valid')
} catch (e) {
  console.error('❌ JSON parse error:', e.message)
  process.exit(1)
}

// 2. Build
console.log('🔨 Building...')
execSync('npx vite build', { cwd: root, stdio: 'inherit' })

// 3. Copy public assets into dist
console.log('📁 Copying assets...')
;['audio', 'images', 'scenes', 'subtitles'].forEach((dir) => {
  const src = path.join(root, 'public', dir)
  const dest = path.join(dist, dir)
  if (fs.existsSync(src)) {
    // Use Node.js fs module for cross-platform compatibility
    copyRecursiveSync(src, dest)
  }
})

// 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)
  }
}

// 4. Zip
console.log('📦 Creating zip...')
fs.rmSync(release, { recursive: true, force: true })
fs.mkdirSync(release, { recursive: true })

const outName = 'mygame'
const zip = new AdmZip()

// Add all files from dist directory to the zip
const addFilesToZip = (dir) => {
  const files = fs.readdirSync(dir)
  files.forEach((file) => {
    const filePath = path.join(dir, file)
    const stat = fs.statSync(filePath)
    if (stat.isDirectory()) {
      addFilesToZip(filePath)
    } else {
      const relativePath = path.relative(dist, filePath)
      zip.addLocalFile(filePath, '', relativePath)
    }
  })
}

addFilesToZip(dist)

// Write the zip file
const zipPath = path.join(release, `${outName}.zip`)
zip.writeZip(zipPath)
console.log(`✅ Packaged: release/${outName}.zip`)
