import { contextBridge, ipcRenderer } from "electron";
import {
  IPC_CHANNELS,
  type ChatAttachment,
  type ChatStreamListener,
  type ConfigSecretId,
  type DesktopApi,
  type RuntimeCloudFetchAction,
  type SaveConfigInput,
  type SignInInput
} from "@qjclaw/shared-types";

const desktopApi: DesktopApi = {
  workspace: {
    getSummary: () => ipcRenderer.invoke(IPC_CHANNELS.workspaceGetSummary),
    warmup: () => ipcRenderer.invoke(IPC_CHANNELS.workspaceWarmup)
  },
  window: {
    minimize: () => ipcRenderer.invoke(IPC_CHANNELS.windowMinimize),
    maximize: () => ipcRenderer.invoke(IPC_CHANNELS.windowMaximize),
    close: () => ipcRenderer.invoke(IPC_CHANNELS.windowClose)
  },
  gateway: {
    status: () => ipcRenderer.invoke(IPC_CHANNELS.gatewayStatus),
    connect: () => ipcRenderer.invoke(IPC_CHANNELS.gatewayConnect),
    disconnect: () => ipcRenderer.invoke(IPC_CHANNELS.gatewayDisconnect),
    reconnect: () => ipcRenderer.invoke(IPC_CHANNELS.gatewayReconnect),
    health: () => ipcRenderer.invoke(IPC_CHANNELS.gatewayHealth),
    tailLogs: (limit?: number) => ipcRenderer.invoke(IPC_CHANNELS.gatewayTailLogs, limit)
  },
  runtime: {
    getStatus: () => ipcRenderer.invoke(IPC_CHANNELS.runtimeGetStatus),
    tailLogs: (limit?: number) => ipcRenderer.invoke(IPC_CHANNELS.runtimeTailLogs, limit),
    start: () => ipcRenderer.invoke(IPC_CHANNELS.runtimeStart),
    stop: () => ipcRenderer.invoke(IPC_CHANNELS.runtimeStop),
    restart: () => ipcRenderer.invoke(IPC_CHANNELS.runtimeRestart),
    health: () => ipcRenderer.invoke(IPC_CHANNELS.runtimeHealth)
  },
  runtimeCloud: {
    getStatus: () => ipcRenderer.invoke(IPC_CHANNELS.runtimeCloudGetStatus),
    fetchConfig: (action?: RuntimeCloudFetchAction) => ipcRenderer.invoke(IPC_CHANNELS.runtimeCloudFetchConfig, action)
  },
  runtimeTelemetry: {
    getStatus: () => ipcRenderer.invoke(IPC_CHANNELS.runtimeTelemetryGetStatus)
  },
  config: {
    load: () => ipcRenderer.invoke(IPC_CHANNELS.configLoad),
    pickWorkspaceDirectory: (currentPath?: string) => ipcRenderer.invoke(IPC_CHANNELS.configPickWorkspaceDirectory, currentPath),
    save: (input: SaveConfigInput) => ipcRenderer.invoke(IPC_CHANNELS.configSave, input),
    revealSecret: (secretId: ConfigSecretId) => ipcRenderer.invoke(IPC_CHANNELS.configRevealSecret, secretId)
  },
  projects: {
    list: () => ipcRenderer.invoke(IPC_CHANNELS.projectsList),
    setActive: (projectId: string) => ipcRenderer.invoke(IPC_CHANNELS.projectsSetActive, projectId),
    resolveIntent: (prompt: string, currentProjectId?: string) => ipcRenderer.invoke(IPC_CHANNELS.projectsResolveIntent, prompt, currentProjectId)
  },
  skillCatalog: {
    list: () => ipcRenderer.invoke(IPC_CHANNELS.skillCatalogList)
  },
  auth: {
    getSessionSummary: () => ipcRenderer.invoke(IPC_CHANNELS.authGetSession),
    signIn: (input: SignInInput) => ipcRenderer.invoke(IPC_CHANNELS.authSignIn, input),
    signOut: () => ipcRenderer.invoke(IPC_CHANNELS.authSignOut)
  },
  profile: {
    getSummary: () => ipcRenderer.invoke(IPC_CHANNELS.profileGetSummary)
  },
  credits: {
    getSummary: () => ipcRenderer.invoke(IPC_CHANNELS.creditsGetSummary)
  },
  skills: {
    list: () => ipcRenderer.invoke(IPC_CHANNELS.skillsList)
  },
  experts: {
    list: () => ipcRenderer.invoke(IPC_CHANNELS.expertsList)
  },
  modelConfig: {
    getSummary: () => ipcRenderer.invoke(IPC_CHANNELS.modelConfigGetSummary)
  },
  system: {
    getSummary: () => ipcRenderer.invoke(IPC_CHANNELS.systemGetSummary)
  },
  tasks: {
    listByDate: (date: string) => ipcRenderer.invoke(IPC_CHANNELS.tasksListByDate, date)
  },
  chat: {
    listSessions: () => ipcRenderer.invoke(IPC_CHANNELS.chatListSessions),
    listSessionsByProject: (projectId: string) => ipcRenderer.invoke(IPC_CHANNELS.chatListSessionsByProject, projectId),
    createSession: (title?: string) => ipcRenderer.invoke(IPC_CHANNELS.chatCreateSession, title),
    createSessionForProject: (projectId: string, title?: string) => ipcRenderer.invoke(IPC_CHANNELS.chatCreateSessionForProject, projectId, title),
    closeSession: (sessionId: string) => ipcRenderer.invoke(IPC_CHANNELS.chatCloseSession, sessionId),
    listMessages: (sessionId: string) => ipcRenderer.invoke(IPC_CHANNELS.chatListMessages, sessionId),
    pickAttachments: () => ipcRenderer.invoke(IPC_CHANNELS.chatPickAttachments),
    pickImageAttachment: () => ipcRenderer.invoke(IPC_CHANNELS.chatPickImageAttachment),
    readImageAttachmentDataUrl: (attachment: ChatAttachment) => ipcRenderer.invoke(IPC_CHANNELS.chatReadImageAttachmentDataUrl, attachment),
    sendPrompt: (sessionId: string, prompt: string, skillId?: string, attachments?: ChatAttachment[]) => ipcRenderer.invoke(IPC_CHANNELS.chatSendPrompt, sessionId, prompt, skillId, attachments),
    streamPrompt: (sessionId: string, prompt: string, skillId?: string, attachments?: ChatAttachment[]) => ipcRenderer.invoke(IPC_CHANNELS.chatStreamPrompt, sessionId, prompt, skillId, attachments),
    onStreamEvent: (listener: ChatStreamListener) => {
      const wrapped = (_event: Electron.IpcRendererEvent, payload: Parameters<ChatStreamListener>[0]) => {
        listener(payload);
      };
      ipcRenderer.on(IPC_CHANNELS.chatStreamEvent, wrapped);
      return () => {
        ipcRenderer.removeListener(IPC_CHANNELS.chatStreamEvent, wrapped);
      };
    }
  },
  diagnostics: {
    openControlUi: () => ipcRenderer.invoke(IPC_CHANNELS.diagnosticsOpenControlUi),
    exportSnapshot: () => ipcRenderer.invoke(IPC_CHANNELS.diagnosticsExportSnapshot)
  }
};

const smokeEnabled = process.argv.includes("--qjc-smoke") || Boolean(process.env.QJCLAW_SMOKE_OUTPUT?.trim());

contextBridge.exposeInMainWorld("qjcDesktop", desktopApi);
contextBridge.exposeInMainWorld("qjcSmokeEnabled", smokeEnabled);
