import esbuild from 'esbuild'
import fs from 'fs'
import path from 'path'

const isProduction = process.env.NODE_ENV === 'production'

// 读取 package.json 中的所有依赖
const packageJson = JSON.parse(fs.readFileSync('package.json', 'utf-8'))
const allDeps = {
  ...packageJson.dependencies,
  ...packageJson.devDependencies,
}
// 开发模式将依赖标记为 external 以加快构建速度；
// 生产模式全部打包进 bundle，runner 阶段无需 node_modules。
const externalModules = isProduction ? [] : Object.keys(allDeps)

const config = {
  entryPoints: ['src/index.ts'],
  bundle: true,
  platform: 'node',
  target: 'esnext',
  format: 'esm',
  outfile: 'dist/index.js',
  external: externalModules,
  sourcemap: !isProduction,
  minify: isProduction,
  // CJS 包（如 dotenv）在 ESM bundle 中需要 require 支持
  banner: isProduction
    ? {
        js: `import{createRequire}from'module';const require=createRequire(import.meta.url);`,
      }
    : {},
  define: {
    'process.env.NODE_ENV': `"${process.env.NODE_ENV || 'development'}"`,
  },
}

async function build() {
  try {
    console.log('Building with esbuild...')
    await esbuild.build(config)

    // 生成 package.json
    const packageJson = { type: 'module' }
    fs.mkdirSync(path.dirname('dist/package.json'), { recursive: true })
    fs.writeFileSync('dist/package.json', JSON.stringify(packageJson, null, 2))

    console.log('✓ Build complete!')
    console.log(`  Entry: ${config.entryPoints[0]}`)
    console.log(`  Output: ${config.outfile}`)
    console.log(`  Mode: ${isProduction ? 'production' : 'development'}`)
    console.log(
      `  Size: ${(fs.statSync(config.outfile).size / 1024).toFixed(1)}KB`,
    )
  } catch (error) {
    console.error('✗ Build failed:', error.message)
    process.exit(1)
  }
}

build()
