const fs = require('fs');

try {
  const data = fs.readFileSync('son.json', 'utf8');
  let json;
  try {
    json = JSON.parse(data);
  } catch (e) {
    console.error('JSON Syntax Error:', e.message);
    process.exit(1);
  }

  if (!Array.isArray(json)) {
    console.error('Root element is not an array');
    process.exit(1);
  }

  const ids = new Set();
  const errors = [];
  const warnings = [];

  json.forEach((item, index) => {
    // Check ID
    if (item.id === undefined) {
      errors.push(`Item at index ${index} missing 'id'`);
    } else {
      if (ids.has(item.id)) {
        errors.push(`Duplicate ID found: ${item.id} at index ${index}`);
      }
      ids.add(item.id);
    }

    // Check required fields
    const requiredFields = [
      'phrase',
      'mean',
      'definition',
      'sampleSentence',
      'difficulty',
      'level',
      'audio',
      'pronunciation',
      'sampleSentenceTr',
      'pronunciationTr',
    ];
    requiredFields.forEach((field) => {
      if (
        item[field] === undefined ||
        item[field] === null ||
        item[field] === ''
      ) {
        // Some fields might be optionally empty, but let's flag empty strings for now as warnings
        if (item[field] === '') {
          warnings.push(
            `Item ID ${item.id || 'index ' + index}: Field '${field}' is empty`
          );
        } else {
          errors.push(
            `Item ID ${item.id || 'index ' + index}: Missing field '${field}'`
          );
        }
      }
    });

    // Check sample sentences length mismatch
    if (
      Array.isArray(item.sampleSentence) &&
      Array.isArray(item.sampleSentenceTr)
    ) {
      if (item.sampleSentence.length !== item.sampleSentenceTr.length) {
        warnings.push(
          `Item ID ${item.id}: Mismatch in sample sentences count (En: ${item.sampleSentence.length}, Tr: ${item.sampleSentenceTr.length})`
        );
      }
    } else {
      if (!Array.isArray(item.sampleSentence))
        errors.push(`Item ID ${item.id}: sampleSentence is not an array`);
      if (!Array.isArray(item.sampleSentenceTr))
        errors.push(`Item ID ${item.id}: sampleSentenceTr is not an array`);
    }
  });

  console.log('Validation Complete.');
  console.log(`Total items: ${json.length}`);
  console.log(`Errors: ${errors.length}`);
  console.log(`Warnings: ${warnings.length}`);

  if (errors.length > 0) {
    console.log('\n--- ERRORS ---');
    errors.slice(0, 50).forEach((e) => console.log(e));
    if (errors.length > 50)
      console.log(`... and ${errors.length - 50} more errors.`);
  }

  if (warnings.length > 0) {
    console.log('\n--- WARNINGS ---');
    warnings.slice(0, 50).forEach((w) => console.log(w));
    if (warnings.length > 50)
      console.log(`... and ${warnings.length - 50} more warnings.`);
  }
} catch (err) {
  console.error('File read error:', err);
}
