const { execSync } = require('child_process')
const fs = require('fs')
const path = require('path')

// 定义 proto 文件所在的目录
// const protoDir = '../assets/resources/proto'
const protoDir = path.join(__dirname, '../assets/resources/proto') // 使用绝对路径
const outputDir = path.join(__dirname, '../assets/scripts/pb') // 输出到同一目录，或单独指定目录

// 读取 proto 目录下的所有文件
fs.readdirSync(protoDir).forEach((file) => {
  if (path.extname(file) === '.proto') {
    const protoFilePath = path.join(protoDir, file)
    const baseName = path.basename(file, '.proto')

    // 生成文件时指定完整输出路径
    const jsOutputPath = path.join(outputDir, `${baseName}.js`)
    const tsOutputPath = path.join(outputDir, `${baseName}.d.ts`)

    // 生成 JavaScript 文件
    // const jsOutputPath = `${baseName}.js`
    execSync(`pbjs -t static-module -w commonjs --force-long=string -o ${jsOutputPath} ${protoFilePath}`)
    // execSync(`pbjs -t static-module -w es6 --force-long=string -o ${jsOutputPath} ${protoFilePath}`)

    // 生成 TypeScript 文件
    // const tsOutputPath = `${baseName}.d.ts`
    execSync(`pbts -o ${tsOutputPath} ${jsOutputPath}`)

    console.log(`Generated ${jsOutputPath} and ${tsOutputPath} for ${file}`)
  }
})
