#!/usr/bin/env node
// https://www.permacomputer.com


/**
 * Translation Completeness Verification Script
 * 
 * This script verifies that all language files have the same translation keys
 * as the English reference file. Use this whenever adding new languages or
 * modifying translation keys to ensure consistency.
 * 
 * Usage:
 *   node verify-translations.js
 *   npm run verify-translations (if added to package.json scripts)
 */

import { fileURLToPath } from 'url';
import { dirname, join } from 'path';
import { readFileSync, readdirSync } from 'fs';

const __filename = fileURLToPath(import.meta.url);
const __dirname = dirname(__filename);

// Colors for console output
const colors = {
	reset: '\x1b[0m',
	red: '\x1b[31m',
	green: '\x1b[32m',
	yellow: '\x1b[33m',
	blue: '\x1b[34m',
	cyan: '\x1b[36m',
	bold: '\x1b[1m'
};

function log(message, color = 'reset') {
	console.log(`${colors[color]}${message}${colors.reset}`);
}

/**
 * Extract translation keys from a language file
 */
function extractKeysFromFile(filePath) {
	try {
		const content = readFileSync(filePath, 'utf8');
		
		// Extract the export object using regex
		const exportMatch = content.match(/export\s+const\s+\w+\s*=\s*{([\s\S]*?)};?\s*$/);
		if (!exportMatch) {
			throw new Error('Could not find export object in file');
		}
		
		const objectContent = exportMatch[1];
		
		// Extract all property keys (handles multiline values and comments)
		const keyMatches = objectContent.match(/^\s*([a-zA-Z_$][a-zA-Z0-9_$]*)\s*:/gm);
		if (!keyMatches) {
			return [];
		}
		
		const keys = keyMatches.map(match => {
			const key = match.match(/^\s*([a-zA-Z_$][a-zA-Z0-9_$]*)/)[1];
			return key;
		});
		
		// Remove duplicates and sort
		return [...new Set(keys)].sort();
	} catch (error) {
		throw new Error(`Failed to extract keys from ${filePath}: ${error.message}`);
	}
}

/**
 * Get all language files in the directory
 */
function getLanguageFiles() {
	const files = readdirSync(__dirname);
	return files
		.filter(file => file.endsWith('.js') && 
			file !== 'index.js' && 
			file !== 'verify-translations.js' && 
			file !== 'add-missing-keys.js')
		.sort();
}

/**
 * Main verification function
 */
function verifyTranslations() {
	log('🔍 Translation Completeness Verification', 'cyan');
	log('=' .repeat(50), 'cyan');
	
	const languageFiles = getLanguageFiles();
	const englishFile = 'en.js';
	
	if (!languageFiles.includes(englishFile)) {
		log('❌ Error: English reference file (en.js) not found!', 'red');
		process.exit(1);
	}
	
	// Extract English keys as reference
	let englishKeys;
	try {
		const englishPath = join(__dirname, englishFile);
		englishKeys = extractKeysFromFile(englishPath);
		log(`📚 English reference file contains ${englishKeys.length} keys`, 'blue');
	} catch (error) {
		log(`❌ Error reading English file: ${error.message}`, 'red');
		process.exit(1);
	}
	
	const results = [];
	let totalIssues = 0;
	
	// Check each language file
	for (const file of languageFiles) {
		if (file === englishFile) continue; // Skip English file itself
		
		const languageName = file.replace('.js', '');
		const filePath = join(__dirname, file);
		
		try {
			const languageKeys = extractKeysFromFile(filePath);
			
			// Find missing and extra keys
			const missingKeys = englishKeys.filter(key => !languageKeys.includes(key));
			const extraKeys = languageKeys.filter(key => !englishKeys.includes(key));
			
			const result = {
				language: languageName,
				file: file,
				totalKeys: languageKeys.length,
				missingKeys,
				extraKeys,
				isComplete: missingKeys.length === 0 && extraKeys.length === 0
			};
			
			results.push(result);
			
			if (!result.isComplete) {
				totalIssues++;
			}
			
		} catch (error) {
			log(`❌ Error processing ${file}: ${error.message}`, 'red');
			totalIssues++;
		}
	}
	
	// Display results
	log('\n📊 Verification Results:', 'yellow');
	log('-'.repeat(30), 'yellow');
	
	const completeLanguages = results.filter(r => r.isComplete);
	const incompleteLanguages = results.filter(r => !r.isComplete);
	
	// Show complete languages
	if (completeLanguages.length > 0) {
		log(`\n✅ Complete Languages (${completeLanguages.length}):`, 'green');
		completeLanguages.forEach(result => {
			log(`   ${result.language} (${result.file}) - ${result.totalKeys} keys`, 'green');
		});
	}
	
	// Show incomplete languages with details
	if (incompleteLanguages.length > 0) {
		log(`\n❌ Incomplete Languages (${incompleteLanguages.length}):`, 'red');
		incompleteLanguages.forEach(result => {
			log(`   ${result.language} (${result.file}) - ${result.totalKeys} keys`, 'red');
			
			if (result.missingKeys.length > 0) {
				log(`     Missing keys (${result.missingKeys.length}): ${result.missingKeys.join(', ')}`, 'red');
			}
			
			if (result.extraKeys.length > 0) {
				log(`     Extra keys (${result.extraKeys.length}): ${result.extraKeys.join(', ')}`, 'yellow');
			}
		});
	}
	
	// Summary
	log('\n📋 Summary:', 'bold');
	log(`   Total languages checked: ${results.length}`, 'blue');
	log(`   Complete languages: ${completeLanguages.length}`, 'green');
	log(`   Incomplete languages: ${incompleteLanguages.length}`, incompleteLanguages.length > 0 ? 'red' : 'green');
	log(`   English reference keys: ${englishKeys.length}`, 'blue');
	
	if (totalIssues === 0) {
		log('\n🎉 All languages have complete translations!', 'green');
		process.exit(0);
	} else {
		log(`\n⚠️  Found ${totalIssues} languages with translation issues.`, 'yellow');
		process.exit(1);
	}
}

/**
 * Display help information
 */
function showHelp() {
	log('Translation Completeness Verification Script', 'cyan');
	log('');
	log('This script verifies that all language files in the languages directory');
	log('have the same translation keys as the English reference file (en.js).');
	log('');
	log('Usage:', 'yellow');
	log('  node verify-translations.js', 'green');
	log('  npm run verify-translations', 'green');
	log('');
	log('The script will:', 'yellow');
	log('  1. Read all .js files in the languages directory');
	log('  2. Extract translation keys from each file');
	log('  3. Compare against the English reference');
	log('  4. Report missing or extra keys');
	log('  5. Exit with code 0 if all complete, 1 if issues found');
	log('');
	log('When adding new languages:', 'yellow');
	log('  1. Create a new .js file with the language code name');
	log('  2. Copy the structure from en.js');
	log('  3. Translate all values while keeping the same keys');
	log('  4. Run this script to verify completeness');
}

// Main execution
if (process.argv.includes('--help') || process.argv.includes('-h')) {
	showHelp();
} else {
	verifyTranslations();
}