// Electron main process for the host agent.
// Owns: the consent window, screen-source selection, and OS input injection.
// WebRTC lives in the renderer (it needs a DOM/navigator); input events arrive
// from the renderer over IPC and are injected here.
const { app, BrowserWindow, ipcMain, desktopCapturer, screen } = require('electron');
const path = require('path');
const injector = require('./input/inject');

const SERVER_URL = process.env.SERVER_URL || 'http://localhost:8090';
const ENROLL_TOKEN = process.env.AGENT_ENROLL_TOKEN || '';

let win;

function createWindow() {
  win = new BrowserWindow({
    width: 460,
    height: 560,
    resizable: false,
    title: 'Remote Access Agent',
    webPreferences: {
      preload: path.join(__dirname, 'preload.js'),
      contextIsolation: true,
      nodeIntegration: false,
    },
  });
  win.loadFile(path.join(__dirname, 'renderer', 'agent.html'));
  // Pass config to the renderer once loaded
  win.webContents.on('did-finish-load', () => {
    win.webContents.send('config', { serverUrl: SERVER_URL, enrollToken: ENROLL_TOKEN });
  });
}

// ---- Screen source for getDisplayMedia (Electron requires a handler) ----
function registerDisplayMediaHandler() {
  const { session } = require('electron');
  session.defaultSession.setDisplayMediaRequestHandler((request, callback) => {
    desktopCapturer.getSources({ types: ['screen'] }).then((sources) => {
      // Default to the primary display; production would let the user pick.
      callback({ video: sources[0], audio: 'loopback' });
    });
  }, { useSystemPicker: false });
}

// ---- IPC: renderer forwards remote input events here for OS injection ----
ipcMain.on('inject-input', (_e, evt) => {
  injector.inject(evt);
});
ipcMain.on('session-ended', () => {
  injector.releaseAll();
});
ipcMain.handle('get-primary-size', () => {
  const { size } = screen.getPrimaryDisplay();
  return size;
});

app.whenReady().then(() => {
  registerDisplayMediaHandler();
  createWindow();
  app.on('activate', () => {
    if (BrowserWindow.getAllWindows().length === 0) createWindow();
  });
});

app.on('window-all-closed', () => {
  if (process.platform !== 'darwin') app.quit();
});
