import { spawnSync } from 'node:child_process'
import { dirname, resolve } from 'node:path'
import { fileURLToPath } from 'node:url'

const __filename = fileURLToPath(import.meta.url)
const __dirname = dirname(__filename)

const args = process.argv.slice(2)
const mode = args[0] || 'production'
const keepLogs = args.includes('--keep-logs')

const viteBin = resolve(__dirname, '../node_modules/vite/bin/vite.js')
const versionScript = resolve(__dirname, './generate-version.js')

const buildEnv = {
  ...process.env,
  LIKEI_KEEP_BUILD_LOGS: keepLogs ? 'true' : 'false',
}

function runNodeScript(scriptPath, scriptArgs = []) {
  const result = spawnSync(process.execPath, [scriptPath, ...scriptArgs], {
    stdio: 'inherit',
    env: buildEnv,
  })

  if (result.error) {
    throw result.error
  }

  if (result.status !== 0) {
    process.exit(result.status ?? 1)
  }
}

runNodeScript(viteBin, ['build', '--mode', mode])
runNodeScript(versionScript)
