import { app } from 'electron';
import { configureDesktopBranding } from './desktop-branding-migration';
import { readDesktopSettings } from '../desktop-settings';

export function configureAppFlags(): void {
  configureDesktopBranding();
  linuxSpecificFlags();
  networkFlags();
  setupGpuEncodingFlags();
  chromiumFlags();
}

function chromiumFlags(): void {
  // Allow media autoplay without user gesture
  app.commandLine.appendSwitch('autoplay-policy', 'no-user-gesture-required');

  // Suppress Autofill devtools errors
  app.commandLine.appendSwitch('disable-features', 'Autofill,AutofillAssistant,AutofillServerCommunication');

  // Collect all enabled features into a single switch to avoid later calls overwriting earlier ones
  const enabledFeatures: string[] = [];

  if (process.platform === 'linux') {
    // PipeWire-based audio pipeline for screen share audio capture
    enabledFeatures.push('AudioServiceOutOfProcess');
    // PipeWire-based screen capture so the xdg-desktop-portal system picker works
    enabledFeatures.push('WebRTCPipeWireCapturer');
  }

  const desktopSettings = readDesktopSettings();

  if (process.platform === 'linux' && desktopSettings.vaapiVideoEncode) {
    enabledFeatures.push('VaapiVideoEncode');
  }

  if (enabledFeatures.length > 0) {
    app.commandLine.appendSwitch('enable-features', enabledFeatures.join(','));
  }
}

function linuxSpecificFlags(): void {
  if (process.platform !== 'linux') {
    return;
  }

  // Disable sandbox on Linux to avoid SUID / /tmp shared-memory issues
  app.commandLine.appendSwitch('no-sandbox');
  app.commandLine.appendSwitch('disable-dev-shm-usage');

  // Chromium chooses the Linux Ozone platform before Electron runs this file.
  // The launch scripts pass `--ozone-platform=wayland` up front for Wayland
  // sessions so the browser process selects the correct backend early enough.
}

function networkFlags(): void {
  // Accept self-signed certificates in development (for --ssl dev server)
  if (process.env['SSL'] === 'true') {
    app.commandLine.appendSwitch('ignore-certificate-errors');
  }
}

function setupGpuEncodingFlags(): void {
  const desktopSettings = readDesktopSettings();

  if (!desktopSettings.hardwareAcceleration) {
    app.disableHardwareAcceleration();
  }

  app.commandLine.appendSwitch('enable-gpu-rasterization');
  app.commandLine.appendSwitch('enable-zero-copy');
  app.commandLine.appendSwitch('enable-native-gpu-memory-buffers');
}
