import { spawn } from 'child_process';
import { watch } from 'fs';
import { exec } from 'child_process';
import { dirname } from 'path';
import { fileURLToPath } from 'url';

const __dirname = dirname(fileURLToPath(import.meta.url));

let electronProcess = null;
let isElectronRunning = false;

function runElectron() {
  if (isElectronRunning) {
    electronProcess.kill();
    isElectronRunning = false;
  }

  // Set environment variable for development
  const env = { ...process.env, NODE_ENV: 'development' };

  electronProcess = spawn('electron', ['.'], { 
    stdio: 'inherit',
    env 
  });

  isElectronRunning = true;

  electronProcess.on('close', () => {
    isElectronRunning = false;
  });
}

// Initial build
exec('tsc -p electron/tsconfig.json', (error) => {
  if (error) {
    console.error('Error building Electron files:', error);
    return;
  }

  console.log('Initial Electron build complete');
  runElectron();
});

// Watch for changes
watch('electron', { recursive: true }, (eventType, filename) => {
  if (filename && filename.endsWith('.ts')) {
    console.log(`File ${filename} changed, rebuilding...`);
    
    exec('tsc -p electron/tsconfig.json', (error) => {
      if (error) {
        console.error('Error rebuilding Electron files:', error);
        return;
      }

      console.log('Rebuild complete, restarting Electron...');
      runElectron();
    });
  }
});

// Handle process termination
process.on('SIGINT', () => {
  if (electronProcess) {
    electronProcess.kill();
  }
  process.exit();
});