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

const logger = {
  log: (message, ...args) => {
    // Always log in development, log with context in production
    if (process.env.NODE_ENV !== "production") {
      /* eslint-disable no-console */
      console.log(`[Preload] ${message}`, ...args);
      /* eslint-enable no-console */
    }
  },
  warn: (message, ...args) => {
    // Always log warnings
    /* eslint-disable no-console */
    console.warn(`[Preload] ${message}`, ...args);
    /* eslint-enable no-console */
  },
  error: (message, ...args) => {
    // Always log errors
    /* eslint-disable no-console */
    console.error(`[Preload] ${message}`, ...args);
    /* eslint-enable no-console */
  },
  info: (message, ...args) => {
    // Always log info in development, log with context in production
    if (process.env.NODE_ENV !== "production") {
      /* eslint-disable no-console */
      console.info(`[Preload] ${message}`, ...args);
      /* eslint-enable no-console */
    }
  },
};

// Use a more direct path resolution approach
const getPath = (pathType) => {
  switch (pathType) {
    case "userData":
      return (
        process.env.APPDATA ||
        (process.platform === "darwin"
          ? `${process.env.HOME}/Library/Application Support`
          : `${process.env.HOME}/.local/share`)
      );
    case "home":
      return process.env.HOME;
    case "appPath":
      return process.resourcesPath;
    default:
      return "";
  }
};

logger.info("Preload script starting...");

// Force electron platform in the renderer process
window.process = { env: { VITE_PLATFORM: "electron" } };

try {
  contextBridge.exposeInMainWorld("electronAPI", {
    // Path utilities
    getPath,

    // IPC functions
    send: (channel, data) => {
      const validChannels = ["toMain"];
      if (validChannels.includes(channel)) {
        ipcRenderer.send(channel, data);
      }
    },
    receive: (channel, func) => {
      const validChannels = ["fromMain"];
      if (validChannels.includes(channel)) {
        ipcRenderer.on(channel, (event, ...args) => func(...args));
      }
    },
    // Environment info
    env: {
      isElectron: true,
      isDev: process.env.NODE_ENV === "development",
      platform: "electron", // Explicitly set platform
    },
    // Path utilities
    getBasePath: () => {
      return process.env.NODE_ENV === "development" ? "/" : "./";
    },
  });

  logger.info("Preload script completed successfully");
} catch (error) {
  logger.error("Error in preload script:", error);
}
