const fs = require('fs');

let corrupted = fs.readFileSync('d:/برنامج مخازن/index.html');
// Try to reverse the PowerShell double encoding.
// If it was read as Windows-1252 and saved as UTF-8:
// The bytes currently in the file are the UTF-8 encoding of the Windows-1252 characters.
// So if we read the file as UTF-8 string, and then convert that string to a buffer using Latin1 (which maps 1:1 to bytes 0-255), we might get back the original UTF-8 bytes!
let str = corrupted.toString('utf8');
let buf = Buffer.from(str, 'latin1');
let recoveredUtf8 = buf.toString('utf8');

// Also try windows-1256
const iconv = require('iconv-lite');
let buf1256 = iconv.encode(str, 'win1256');
let recovered1256 = buf1256.toString('utf8');

console.log("Latin1 recovery preview:", recoveredUtf8.substring(0, 200).replace(/\n/g, ' '));
console.log("Win1256 recovery preview:", recovered1256.substring(0, 200).replace(/\n/g, ' '));

// Let's just output the first few Arabic words.
console.log("Original match:", recoveredUtf8.match(/[\u0600-\u06FF]+/g));
console.log("Win1256 match:", recovered1256.match(/[\u0600-\u06FF]+/g));
