import { readFileSync, writeFileSync, existsSync, mkdirSync } from 'fs';

import checkIsThisLocale from './checkIsThisLocale'
import { extractTextFields } from './extractText'

// const text1 = "营业時間";
// const text2 = "萬事如意";
// const text3 = "Hello world!";
// const text4 = "你好World";
// const text5 = "營業時間";

// console.log(await checkIsThisLocale(text1, "zh"));       // ✅ true
// console.log(await checkIsThisLocale(text2, "zh-hant"));  // ✅ true
// console.log(await checkIsThisLocale(text3, "en"));       // ✅ true
// console.log(await checkIsThisLocale(text4, "zh"));
// console.log(await checkIsThisLocale(text5, "zh-hant"));
// console.log(await checkIsThisLocale(text5, "zh"));


const locale = "zh-hant" || "zh";


const outputPath = 'static/aiSectionScripts/tasks/firstSection/checki18n/data/checkresult.json'




async function appendToJsonFile(newData: any, filename: string, path: string) {


  const mainPath = path || 'static/data/templates'; // 默认路径
  const filePath = `${mainPath}/${filename}.json`; // 确保文件路径正确
  try {
    const raw = await readFileSync(filePath, 'utf-8');
    let jsonArray = JSON.parse(raw);

    if (!Array.isArray(jsonArray)) {
      throw new Error('JSON 文件格式错误，不是数组');
    }

    if (Array.isArray(newData)) {
      jsonArray = jsonArray.concat(newData);
    } else {
      jsonArray.push(newData);
    }

    await writeFileSync(filePath, JSON.stringify(jsonArray, null, 2), 'utf-8');
    return true
  } catch (err) {
    console.error('❌ 写入失败:', err);
    return false
  }
}





async function runAll() {

  const promptPath = 'static/aiSectionScripts/tasks/firstSection/checki18n/data/prompts.json'

  const prompts = JSON.parse(readFileSync(promptPath, 'utf8'));



  for (const prompt of prompts) {

    const output_cn = readFileSync(`static/aiSectionScripts/tasks/firstSection/checki18n/data/cn/${prompt.name}.json`, 'utf8');
    const output_tw = readFileSync(`static/aiSectionScripts/tasks/firstSection/checki18n/data/tw/${prompt.name}.json`, 'utf8');
    const result_cn = await Promise.all(
      JSON.parse(output_cn).map(async (item) => {
        const texts = extractTextFields(item).join(';');
        const check = await checkIsThisLocale(texts, 'zh');
        return check;
      }))

    const result_tw = await Promise.all(
      JSON.parse(output_tw).map(async (item) => {
        const texts = extractTextFields(item).join(';');
        const check = await checkIsThisLocale(texts, 'zh-hant');
        return check;
      }))

    const data = {
      [prompt.name]: {
        cn: result_cn,
        tw: result_tw,
      }
    }
    await appendToJsonFile(data, 'checkresult', `static/aiSectionScripts/tasks/firstSection/checki18n/data`);

    console.log(`写入：${prompt.name}`)

  }
}


runAll()