import { contextBridge, ipcRenderer, shell } from 'electron'
import { electronAPI } from '@electron-toolkit/preload'
import api from './api'
import { pathToFileURL } from 'node:url'
import path from 'node:path'
import fs from "node:fs";


async function resolveSound(fileName: string) {
  const resourcesPath = await ipcRenderer.invoke('runtime:get-resources');
  const fullPath = path.join(resourcesPath, "sounds", fileName);
  if (!fs.existsSync(fullPath)) {
    throw new Error(`Sound not found: ${fullPath}`);
  }
  return pathToFileURL(fullPath).toString();
}

const exposeContext = async () => {
	if (process.contextIsolated) {
		try {
			contextBridge.exposeInMainWorld('electron', electronAPI)
			contextBridge.exposeInMainWorld('api', api)
			contextBridge.exposeInMainWorld('shell', {
				openExternal: (url: string) => {
					ipcRenderer.invoke('ipcCore:openExternal', url);
				},
				showItemInFolder: (fullPath: string) => {
					ipcRenderer.invoke('ipcCore:showItemInFolder', fullPath);
				}
			});
			contextBridge.exposeInMainWorld("mediaApi", {
				getSoundUrl: async (fileName: string) => {
					return resolveSound(fileName);
				}
			});
		} catch (error) {
			console.error(error)
		}
	} else {
		window.electron = electronAPI
		window.api = api;
		window.shell = shell;
		window.mediaApi = {
			getSoundUrl: async (fileName: string) => {
				return resolveSound(fileName);
			}
		}
	}
}

exposeContext();