const { execSync } = require('child_process');
const readline = require('readline');

console.log('Windows Insider Program Removal Tool (IRT)');

// Disclaimer
console.log(`
By using this script, you agree that the author is not responsible for any damage or loss resulting from its use. 
The script is provided "as is" without any warranties. Use at your own risk. 
The author is not liable for any direct, indirect, incidental, special, exemplary, or consequential damages. 
You acknowledge that any harm, whether intentional or accidental, is your own responsibility. 
By continuing to use this script, you automatically agree to these terms and waive any claims for damages against the author.
`);

// Check if the script is running as administrator
try {
  execSync('net session', { stdio: 'ignore' });
} catch (err) {
  console.error('Please run the script as an administrator.');
  process.exit(1);
}

// Remove Windows Insider settings
console.log('Removing Windows Insider settings...');
try {
  execSync('reg delete "HKLM\\SOFTWARE\\Microsoft\\WindowsSelfHost" /f', { stdio: 'ignore' });
  console.log('Windows Insider settings removed.');
} catch (err) {
  console.log('Windows Insider settings not found.');
}

// Remove the registration key
console.log('Removing the Windows Insider registration key...');
try {
  execSync('reg delete "HKCU\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Policies\\DataCollection" /f', { stdio: 'ignore' });
  console.log('Registration key removed.');
} catch (err) {
  console.log('Registration key not found.');
}

// Restart Windows Update service
console.log('Restarting Windows Update service...');
try {
  execSync('net stop wuauserv', { stdio: 'inherit' });
  execSync('net start wuauserv', { stdio: 'inherit' });
  console.log('Windows Update service restarted.');
} catch (err) {
  console.error('Failed to restart Windows Update service.');
  process.exit(1);
}

console.log('Windows Insider Program successfully removed.');

// Display Windows information
console.log('Displaying Windows information...');
try {
  const windowsProductName = execSync('reg query "HKLM\\SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion" /v ProductName').toString();
  const windowsBuildLabEx = execSync('reg query "HKLM\\SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion" /v BuildLabEx').toString();
  const productName = windowsProductName.match(/ProductName\s+REG_SZ\s+(.+)/)[1];
  const buildLabEx = windowsBuildLabEx.match(/BuildLabEx\s+REG_SZ\s+(.+)/)[1];
  console.log(`${productName} (${buildLabEx})`);
} catch (err) {
  console.error('Failed to retrieve Windows information.');
}

// Display Windows product key
let productKey;
try {
  productKey = execSync('powershell -Command "(Get-WmiObject -query \\"select * from SoftwareLicensingService\\").OA3xOriginalProductKey"').toString().trim();
  if (!productKey) {
    throw new Error('Product key not found');
  }
  console.log(`Windows Product Key: ${productKey}`);
} catch (err) {
  console.error('Failed to retrieve Windows product key. Checking backup key...');
  try {
    const backupProductKey = execSync('reg query "HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\SoftwareProtectionPlatform" /v BackupProductKeyDefault').toString();
    const backupKey = backupProductKey.match(/BackupProductKeyDefault\s+REG_SZ\s+(.+)/)[1];
    console.log(`Backup Windows Product Key: ${backupKey}`);
  } catch (backupErr) {
    console.error('Failed to retrieve backup Windows product key.');
  }
}

// Prompt user for DISM /RestoreHealth and sfc /scannow
const rl = readline.createInterface({
  input: process.stdin,
  output: process.stdout
});

console.log('Would you like to run DISM /RestoreHealth and sfc /scannow? Select within 10 seconds! (1-Yes, 0-No)');

let timer = setTimeout(() => {
  console.log('No response detected in 10 seconds. Stopping script...');
  rl.close();
}, 10000);

rl.on('line', (input) => {
  clearTimeout(timer);
  if (input.trim() === '1') {
    console.log('Running DISM /RestoreHealth...');
    execSync('DISM.exe /Online /Cleanup-Image /RestoreHealth', { stdio: 'inherit' });
    console.log('Running sfc /scannow...');
    execSync('sfc.exe /scannow', { stdio: 'inherit' });
    console.log('DISM /RestoreHealth and sfc /scannow completed.');
  } else {
    console.log('DISM /RestoreHealth and sfc /scannow skipped.');
  }
  rl.close();
});