const fs = require('fs');
const path = require('path');
const { execSync } = require('child_process');

const desktopPath = path.join(process.env.USERPROFILE, 'Desktop');
const targetHtml = path.join(__dirname, 'index.html');

console.log('Desktop path:', desktopPath);

// List of possible browser executables
const possibleBrowsers = [
  'C:\\Program Files\\Google\\Chrome\\Application\\chrome.exe',
  'C:\\Program Files (x86)\\Google\\Chrome\\Application\\chrome.exe',
  path.join(process.env.LOCALAPPDATA || '', 'Google\\Chrome\\Application\\chrome.exe'),
  'C:\\Program Files (x86)\\Microsoft\\Edge\\Application\\msedge.exe',
  'C:\\Program Files\\Microsoft\\Edge\\Application\\msedge.exe',
  'C:\\Program Files\\BraveSoftware\\Brave-Browser\\Application\\brave.exe',
  path.join(process.env.LOCALAPPDATA || '', 'BraveSoftware\\Brave-Browser\\Application\\brave.exe')
];

let browserPath = '';
for (const b of possibleBrowsers) {
  if (fs.existsSync(b)) {
    browserPath = b;
    break;
  }
}

console.log('Detected Browser:', browserPath);

// Remove bad shortcuts from desktop if any
const badFiles = fs.readdirSync(desktopPath);
for (const f of badFiles) {
  if (f.startsWith('b,b') || f === 'Quran App.lnk' || f.includes('القرآن الكريم')) {
    try {
      fs.unlinkSync(path.join(desktopPath, f));
      console.log('Removed old shortcut:', f);
    } catch (e) {}
  }
}

// Prepare VBS script to create reliable shortcut
const vbsScript = path.join(__dirname, 'create_lnk.vbs');
let vbsContent = '';

if (browserPath) {
  vbsContent = `
Set WshShell = CreateObject("WScript.Shell")
strDesktop = WshShell.SpecialFolders("Desktop")
Set oShortcut = WshShell.CreateShortcut(strDesktop & "\\Quran App.lnk")
oShortcut.TargetPath = "${browserPath.replace(/\\/g, '\\\\')}"
oShortcut.Arguments = "--app=""file:///${targetHtml.replace(/\\/g, '/') }"""
oShortcut.WorkingDirectory = "${__dirname.replace(/\\/g, '\\\\')}"
oShortcut.Description = "تطبيق القرآن الكريم والأذكار"
oShortcut.Save
`;
} else {
  // Fallback to default browser opener
  vbsContent = `
Set WshShell = CreateObject("WScript.Shell")
strDesktop = WshShell.SpecialFolders("Desktop")
Set oShortcut = WshShell.CreateShortcut(strDesktop & "\\Quran App.lnk")
oShortcut.TargetPath = "explorer.exe"
oShortcut.Arguments = """${targetHtml.replace(/\\/g, '\\\\')}"""
oShortcut.WorkingDirectory = "${__dirname.replace(/\\/g, '\\\\')}"
oShortcut.Description = "تطبيق القرآن الكريم والأذكار"
oShortcut.Save
`;
}

fs.writeFileSync(vbsScript, vbsContent, 'utf8');
execSync(`cscript //nologo "${vbsScript}"`);

console.log('Shortcut created successfully on Desktop!');
