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

async function main() {
  try {
    console.log('Starting electron build process...');

    // Create dist directory if it doesn't exist
    const distElectronDir = path.resolve(__dirname, '../dist-electron');
    await fs.ensureDir(distElectronDir);

    // Copy web files
    const wwwDir = path.join(distElectronDir, 'www');
    await fs.ensureDir(wwwDir);
    await fs.copy('dist', wwwDir);

    // Copy and fix index.html
    const indexPath = path.join(wwwDir, 'index.html');
    let indexContent = await fs.readFile(indexPath, 'utf8');

    // More comprehensive path fixing
    indexContent = indexContent
      // Fix absolute paths to be relative
      .replace(/src="\//g, 'src="\./')
      .replace(/href="\//g, 'href="\./')
      // Fix modulepreload paths
      .replace(/<link [^>]*rel="modulepreload"[^>]*href="\/assets\//g, '<link rel="modulepreload" as="script" crossorigin="" href="./assets/')
      .replace(/<link [^>]*rel="modulepreload"[^>]*href="\.\/assets\//g, '<link rel="modulepreload" as="script" crossorigin="" href="./assets/')
      // Fix stylesheet paths
      .replace(/<link [^>]*rel="stylesheet"[^>]*href="\/assets\//g, '<link rel="stylesheet" crossorigin="" href="./assets/')
      .replace(/<link [^>]*rel="stylesheet"[^>]*href="\.\/assets\//g, '<link rel="stylesheet" crossorigin="" href="./assets/')
      // Fix script paths
      .replace(/src="\/assets\//g, 'src="./assets/')
      .replace(/src="\.\/assets\//g, 'src="./assets/')
      // Fix any remaining asset paths
      .replace(/(['"]\/?)(assets\/)/g, '"./assets/');

    // Debug output
    console.log('After path fixing, checking for remaining /assets/ paths:', indexContent.includes('/assets/'));
    console.log('Sample of fixed content:', indexContent.slice(0, 500));

    await fs.writeFile(indexPath, indexContent);
    
    console.log('Copied and fixed web files in:', wwwDir);

    // Copy main process files
    console.log('Copying main process files...');
    const mainProcessFiles = [
      ['src/electron/main.js', 'main.js'],
      ['src/electron/preload.js', 'preload.js']
    ];

    for (const [src, dest] of mainProcessFiles) {
      const destPath = path.join(distElectronDir, dest);
      console.log(`Copying ${src} to ${destPath}`);
      await fs.copy(src, destPath);
    }

    // Create package.json for production
    const devPackageJson = require('../package.json');
    const prodPackageJson = {
      name: devPackageJson.name,
      version: devPackageJson.version,
      description: devPackageJson.description,
      author: devPackageJson.author,
      main: 'main.js',
      private: true,
    };

    await fs.writeJson(
      path.join(distElectronDir, 'package.json'),
      prodPackageJson,
      { spaces: 2 }
    );

    // Verify the build
    console.log('\nVerifying build structure:');
    const files = await fs.readdir(distElectronDir);
    console.log('Files in dist-electron:', files);

    if (!files.includes('main.js')) {
      throw new Error('main.js not found in build directory');
    }
    if (!files.includes('preload.js')) {
      throw new Error('preload.js not found in build directory');
    }
    if (!files.includes('package.json')) {
      throw new Error('package.json not found in build directory');
    }

    console.log('Build completed successfully!');
  } catch (error) {
    console.error('Build failed:', error);
    process.exit(1);
  }
}

main(); 