const fs = require('fs');
const root = "./src"
let allFiles = []
const savePath = "./src/i18n/languages/en_US.json"
const crypto = require('crypto');
const https = require('https');
const querystring = require('querystring');

// 你的百度翻译API的App ID和密钥
const appId = "20230911001813245"
const appKey = "lJlOnktUO0pn8G_MZ10O"

const translateText = (text, fromLang = 'zh', toLang = 'en') => {
  return new Promise((resolve, reject) => {
    // 百度翻译API的接口地址
    const apiUrl = "https://fanyi-api.baidu.com/api/trans/vip/translate";

    // 构建请求参数
    const params = {
      q: text,
      from: fromLang,
      to: toLang,
      appid: appId,
      salt: Math.random().toString().slice(2),
      sign: ''
    };

    // 生成签名
    const signStr = appId + text + params.salt + appKey;
    params.sign = require('crypto').createHash('md5').update(signStr).digest('hex');

    // 发送HTTP POST请求
    const options = {
      hostname: 'fanyi-api.baidu.com',
      port: 443,
      path: '/api/trans/vip/translate',
      method: 'POST',
      headers: {
        'Content-Type': 'application/x-www-form-urlencoded',
        'Content-Length': querystring.stringify(params).length
      }
    };
    try{
      const req = https.request(options, (res) => {
        let data = '';

        res.on('data', (chunk) => {
          data += chunk;
        });

        res.on('end', () => {
          console.log('翻译结果:', data);
          resolve(JSON.parse(data).trans_result[0].dst)
        });
      });

      req.on('error', (err) => {
        console.error(err);
      });

      req.write(querystring.stringify(params));
      req.end();
    }catch (e) {
      console.log(text + " 翻译失败：" + e)
    }

  })
};


function getFiles(dir){
  let files = fs.readdirSync(dir)
  files.forEach(file => {
    let path = dir + '/' + file
    if(fs.lstatSync(path).isDirectory()){
      getFiles(path)
    }else allFiles.push(path)
  })
}

getFiles(root)
let messages = new Set()
allFiles.forEach(file => {
  let data = fs.readFileSync(file, {encoding: 'utf-8'})
  let matched = data.matchAll(/\$t\([\'\"]{1}([^\"\']+)[\'\"]{1}/g)
  let i = 0
  for(let item of matched){
    i ++
    messages.add(item[1])
  }
})

let obj = require(savePath)
Array.from(messages).forEach(word => {
  if(!obj[word])obj[word] = ""
})

let autoTransCnt = 0
async function translate(obj){
  // 对未翻译内容调用百度翻译进行翻译操作，有变量的不做处理
  for(let text in obj){
    if(obj[text] || text.trim() === '')continue
    try{
      const textEn = await translateText(text)
      console.log(`${text} => ${textEn}\n`)
      obj[text] = textEn
      autoTransCnt ++

      // 每次翻译后保存一次，防止意外退出导致的数据丢失
      fs.writeFileSync(savePath, JSON.stringify(obj, null, 4))
    }catch (e) {
      console.log(text + " 翻译失败：" + e)
    }


    // 账号请求频率限制1ps
    await new Promise(resolve => setTimeout(resolve, 1000))
  }
}
translate(obj).then(res => {
  fs.writeFileSync(savePath, JSON.stringify(obj, null, 4))
  console.log(messages)
  console.warn(`本次共提取 ${messages.size} 个待翻译内容，保存于${savePath}`)
  console.log(`已调用百度api自动翻译 ${autoTransCnt} 个内容\n`)
  console.log("done!")
})
