const fs = require('fs');
const path = require('path');

console.log('Starting electron build process...');

// Define paths
const electronDistPath = path.join(__dirname, '..', 'dist-electron');
const wwwPath = path.join(electronDistPath, 'www');

// Create www directory if it doesn't exist
if (!fs.existsSync(wwwPath)) {
  fs.mkdirSync(wwwPath, { recursive: true });
}

// Create a platform-specific index.html for Electron
const initialIndexContent = `<!DOCTYPE html>
<html lang="">
  <head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width,initial-scale=1.0,viewport-fit=cover">
    <link rel="icon" href="/favicon.ico">
    <title>TimeSafari</title>
  </head>
  <body>
    <noscript>
      <strong>We're sorry but TimeSafari doesn't work properly without JavaScript enabled. Please enable it to continue.</strong>
    </noscript>
    <div id="app"></div>
    <script type="module">
      // Force electron platform
      window.process = { env: { VITE_PLATFORM: 'electron' } };
      import('./src/main.electron.ts');
    </script>
  </body>
</html>`;

// Write the Electron-specific index.html
fs.writeFileSync(path.join(wwwPath, 'index.html'), initialIndexContent);

// Copy only necessary assets from web build
const webDistPath = path.join(__dirname, '..', 'dist');
if (fs.existsSync(webDistPath)) {
  // Copy assets directory
  const assetsSrc = path.join(webDistPath, 'assets');
  const assetsDest = path.join(wwwPath, 'assets');
  if (fs.existsSync(assetsSrc)) {
    fs.cpSync(assetsSrc, assetsDest, { recursive: true });
  }
  
  // Copy favicon
  const faviconSrc = path.join(webDistPath, 'favicon.ico');
  if (fs.existsSync(faviconSrc)) {
    fs.copyFileSync(faviconSrc, path.join(wwwPath, 'favicon.ico'));
  }
}

// Remove service worker files
const swFilesToRemove = [
  'sw.js',
  'sw.js.map',
  'workbox-*.js',
  'workbox-*.js.map',
  'registerSW.js',
  'manifest.webmanifest',
  '**/workbox-*.js',
  '**/workbox-*.js.map',
  '**/sw.js',
  '**/sw.js.map',
  '**/registerSW.js',
  '**/manifest.webmanifest'
];

console.log('Removing service worker files...');
swFilesToRemove.forEach(pattern => {
  const files = fs.readdirSync(wwwPath).filter(file => 
    file.match(new RegExp(pattern.replace(/\*/g, '.*')))
  );
  files.forEach(file => {
    const filePath = path.join(wwwPath, file);
    console.log(`Removing ${filePath}`);
    try {
      fs.unlinkSync(filePath);
    } catch (err) {
      console.warn(`Could not remove ${filePath}:`, err.message);
    }
  });
});

// Also check and remove from assets directory
const assetsPath = path.join(wwwPath, 'assets');
if (fs.existsSync(assetsPath)) {
  swFilesToRemove.forEach(pattern => {
    const files = fs.readdirSync(assetsPath).filter(file => 
      file.match(new RegExp(pattern.replace(/\*/g, '.*')))
    );
    files.forEach(file => {
      const filePath = path.join(assetsPath, file);
      console.log(`Removing ${filePath}`);
      try {
        fs.unlinkSync(filePath);
      } catch (err) {
        console.warn(`Could not remove ${filePath}:`, err.message);
      }
    });
  });
}

// Modify index.html to remove service worker registration
const indexPath = path.join(wwwPath, 'index.html');
if (fs.existsSync(indexPath)) {
  console.log('Modifying index.html to remove service worker registration...');
  let indexContent = fs.readFileSync(indexPath, 'utf8');
  
  // Remove service worker registration script
  indexContent = indexContent
    .replace(/<script[^>]*id="vite-plugin-pwa:register-sw"[^>]*><\/script>/g, '')
    .replace(/<script[^>]*registerServiceWorker[^>]*><\/script>/g, '')
    .replace(/<link[^>]*rel="manifest"[^>]*>/g, '')
    .replace(/<link[^>]*rel="serviceworker"[^>]*>/g, '')
    .replace(/navigator\.serviceWorker\.register\([^)]*\)/g, '')
    .replace(/if\s*\(\s*['"]serviceWorker['"]\s*in\s*navigator\s*\)\s*{[^}]*}/g, '');
  
  fs.writeFileSync(indexPath, indexContent);
  console.log('Successfully modified index.html');
}

// Fix asset paths
console.log('Fixing asset paths in index.html...');
let modifiedIndexContent = fs.readFileSync(indexPath, 'utf8');
modifiedIndexContent = modifiedIndexContent
  .replace(/\/assets\//g, './assets/')
  .replace(/href="\//g, 'href="./')
  .replace(/src="\//g, 'src="./');

fs.writeFileSync(indexPath, modifiedIndexContent);

// Verify no service worker references remain
const finalContent = fs.readFileSync(indexPath, 'utf8');
if (finalContent.includes('serviceWorker') || finalContent.includes('workbox')) {
  console.warn('Warning: Service worker references may still exist in index.html');
}

// Check for remaining /assets/ paths
console.log('After path fixing, checking for remaining /assets/ paths:', finalContent.includes('/assets/'));
console.log('Sample of fixed content:', finalContent.substring(0, 500));
    
console.log('Copied and fixed web files in:', wwwPath);

// Copy main process files
console.log('Copying main process files...');

// Copy the main process file instead of creating a template
const mainSrcPath = path.join(__dirname, '..', 'dist-electron', 'main.js');
const mainDestPath = path.join(electronDistPath, 'main.js');

if (fs.existsSync(mainSrcPath)) {
  fs.copyFileSync(mainSrcPath, mainDestPath);
  console.log('Copied main process file successfully');
} else {
  console.error('Main process file not found at:', mainSrcPath);
  process.exit(1);
}

console.log('Electron build process completed successfully');