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

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



function countCharDiff(text1: string, text2: string): number {
    const changes = diffChars(text1, text2);
    let diffCount = 0;
    for (const part of changes) {
        if (part.added || part.removed) {
            diffCount += part.value.length;
        }
    }
    return diffCount;
}


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', true);
                return {
                    result: check.result,
                    text: texts,
                    covert: check.convert,
                    diffCount: countCharDiff(texts, check.convert) / texts.length
                };
            }))

        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', true);
                return {
                    result: check.result,
                    text: texts,
                    covert: check.convert,
                    diffCount: countCharDiff(texts, check.convert) / texts.length
                };
            }))
        const data = {
            [prompt.name]: {
                cn: result_cn.filter(item => !item.result),
                tw: result_tw.filter(item => !item.result),
            }
        }
        await appendToJsonFile(data, 'filterResult', `static/aiSectionScripts/tasks/firstSection/checki18n/data`);

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

    }
}


runAll()