/**
 * Preload script — expose a minimal IPC transport to the renderer.
 *
 * Replaces electron-trpc's exposeElectronTRPC with a compatible shim
 * that works with our custom IPC handler + tRPC v11.
 */
import { contextBridge, ipcRenderer } from 'electron';

const IPC_CHANNEL = 'trpc';

contextBridge.exposeInMainWorld('electronTRPC', {
  sendMessage: (msg: unknown) => ipcRenderer.send(IPC_CHANNEL, msg),
  onMessage: (cb: (data: unknown) => void) => {
    const handler = (_event: Electron.IpcRendererEvent, data: unknown) => cb(data);
    ipcRenderer.on(IPC_CHANNEL, handler);
    return () => {
      ipcRenderer.removeListener(IPC_CHANNEL, handler);
    };
  },
});

const AI_STREAM_CHANNEL = 'ai:stream';

// V3 stream event — discriminated union of all frame types the renderer can receive.
type V3StreamEvent =
  | { type: 'stream_start'; requestId: string }
  | { type: 'stream_text'; requestId: string; chunk: string }
  | { type: 'stream_end'; requestId: string; mutations?: unknown[] }
  | {
      type: 'floating_domain';
      requestId: string;
      domain:
        | 'tasks'
        | 'notes'
        | 'timelines'
        | 'projects'
        | {
            type: 'task' | 'timeline' | 'project' | 'note' | 'node';
            id?: string | null;
            section?: 'task' | 'timeline' | 'note' | null;
          };
    };

contextBridge.exposeInMainWorld('electronAI', {
  /** Subscribe to v3 AI stream events. Returns an unsubscribe function. */
  onStreamEvent: (cb: (data: V3StreamEvent) => void) => {
    const handler = (_event: Electron.IpcRendererEvent, data: V3StreamEvent) => cb(data);
    ipcRenderer.on(AI_STREAM_CHANNEL, handler);
    return () => {
      ipcRenderer.removeListener(AI_STREAM_CHANNEL, handler);
    };
  },
  /** Subscribe to background brief-updated push events. Returns an unsubscribe function. */
  onBriefUpdated: (cb: (content: string) => void) => {
    const handler = (_event: Electron.IpcRendererEvent, content: string) => cb(content);
    ipcRenderer.on('ai:brief-updated', handler);
    return () => {
      ipcRenderer.removeListener('ai:brief-updated', handler);
    };
  },
});

// ---------------------------------------------------------------------------
// Dialog — native file/folder picker
// ---------------------------------------------------------------------------
contextBridge.exposeInMainWorld('electronDialog', {
  showOpenDialog: (options: Electron.OpenDialogOptions): Promise<Electron.OpenDialogReturnValue> =>
    ipcRenderer.invoke('dialog:showOpenDialog', options),
});
