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

import { fetchAzureOpenAIResponse } from './client'



export async function executeOutput(locale: string) {
  const readPath = 'static/aiSectionScripts/tasks/firstSection/checki18n/data/prompts.json';

  if (!existsSync(readPath)) {
    console.error(`File not found: ${readPath}`);
    return;
  }

  const templates = JSON.parse(readFileSync(readPath, 'utf-8'));

  for (const item of templates) {
    const targetPath = `static/aiSectionScripts/tasks/firstSection/checki18n/data/${locale}/${item.name}.json`;

    const prompt = item[`prompt_${locale}`];
    if (!prompt) {
      console.warn(`No prompt for locale "${locale}" in item "${item.name}"`);
      continue;
    }

    for (let i = 0; i < 100; i++) {
      try {
        let outputs: any[] = [];
        if (existsSync(targetPath)) {
          outputs = JSON.parse(readFileSync(targetPath, 'utf-8'));
        }
        const result = await fetchAzureOpenAIResponse(prompt);
        outputs.push(result);
        writeFileSync(targetPath, JSON.stringify(outputs, null, 2), 'utf8');
        console.log(`✅ [${item.name}] written ${i + 1}/100`);
      } catch (err) {
        console.error(`❌ Error on ${item.name} - iteration ${i + 1}:`, err);
      }
    }
  }
}

export async function runAll() {
  await Promise.all([
    executeOutput('cn').catch(err => console.error('cn failed:', err)),
    executeOutput('tw').catch(err => console.error('tw failed:', err)),
  ]);
}

// main().catch(console.error);