const { contextBridge, ipcRenderer } = require('electron');

const env = getPreloadEnv();

contextBridge.exposeInMainWorld('api', {
  env: Object.freeze({
    isDevelopment: env.isDevelopment,
    isProduction: env.isProduction,
    logEnabled: env.logEnabled,
    nodeEnv: env.nodeEnv,
  }),
  selectFolder:       ()         => ipcRenderer.invoke('select-folder'),
  listImages:         (folder)   => ipcRenderer.invoke('list-images', folder),
  readImage:          (path)     => ipcRenderer.invoke('read-image', path),
  renameFiles:        (args)     => ipcRenderer.invoke('rename-files', args),
  onFullscreenChange: (() => {
    let _cb = null;
    ipcRenderer.on('fullscreen-change', (_e, v) => { if (_cb) _cb(v); });
    return (callback) => { _cb = callback; };
  })(),
  getHomeDir:         ()         => ipcRenderer.invoke('get-home-dir'),
  getLastFolder:      ()         => ipcRenderer.invoke('get-last-folder'),
  setLastFolder:      (p)        => ipcRenderer.invoke('set-last-folder', p),
  listDirectories:    (p)        => ipcRenderer.invoke('list-directories', p),
  revealFolder:       (p)        => ipcRenderer.invoke('reveal-folder', p),
  getPreviewOn:       ()         => ipcRenderer.invoke('get-preview-on'),
  setPreviewOn:       (on)       => ipcRenderer.invoke('set-preview-on', on),
  getSidebarWidth:    ()         => ipcRenderer.invoke('get-sidebar-width'),
  setSidebarWidth:    (width)    => ipcRenderer.invoke('set-sidebar-width', width),
  getThumbSize:       ()         => ipcRenderer.invoke('get-thumb-size'),
  setThumbSize:       (size)     => ipcRenderer.invoke('set-thumb-size', size),
  checkFilesExist:    (folder, names) => ipcRenderer.invoke('check-files-exist', folder, names),
  moveFiles:          (args)     => ipcRenderer.invoke('move-files', args),
  stageDeleteFiles:   (paths)    => ipcRenderer.invoke('stage-delete-files', paths),
  restoreStagedFiles: (entries)  => ipcRenderer.invoke('restore-staged-files', entries),
});

function getPreloadEnv() {
  const nodeEnv = normalizeNodeEnv(process.env.NODE_ENV || 'production');
  const isDevelopment = nodeEnv === 'development';
  const isProduction = nodeEnv === 'production';
  const logEnabled = isDevelopment && parseBoolean(process.env.PHOTO_RENAMER_LOGS, true);

  return { isDevelopment, isProduction, logEnabled, nodeEnv };
}

function normalizeNodeEnv(value) {
  return value === 'product' ? 'production' : value;
}

function parseBoolean(value, fallback) {
  if (value === undefined) return fallback;
  return ['1', 'true', 'yes', 'on'].includes(String(value).toLowerCase());
}
