import { contextBridge, ipcRenderer } from "electron";
import type { CaptureOptions, GoodDatabase, ReviewSamplePayload, ScannerStatusPayload, ScannerLearningRulePayload } from "../src/types/global.js";
import type { StoredArtifactRecord } from "../src/types/storage.js";
import type { AppSnapshot } from "../src/types/domain.js";

contextBridge.exposeInMainWorld("assistantApi", {
  loadSnapshot: () => ipcRenderer.invoke("snapshot:load"),
  saveSnapshot: (snapshot: AppSnapshot) => ipcRenderer.invoke("snapshot:save", snapshot),
  runMockScan: () => ipcRenderer.invoke("scan:runMock"),
  listCaptureSources: () => ipcRenderer.invoke("capture:listSources"),
  captureSource: (sourceId: string, delayMs = 0, focusGenshin = false, options?: CaptureOptions) => ipcRenderer.invoke("capture:captureSource", sourceId, delayMs, focusGenshin, options),
  clickScreen: (x: number, y: number) => ipcRenderer.invoke("automation:clickScreen", x, y),
  scrollScreen: (notches: number, anchorX?: number, anchorY?: number) => ipcRenderer.invoke("automation:scrollScreen", notches, anchorX, anchorY),
  getAutomationGuard: () => ipcRenderer.invoke("automation:getGuard"),
  focusMainWindow: () => ipcRenderer.invoke("app:focusMainWindow"),
  focusGenshin: () => ipcRenderer.invoke("automation:focusGenshin"),
  getRuntimeInfo: () => ipcRenderer.invoke("app:getRuntimeInfo"),
  saveReviewSample: (sample: ReviewSamplePayload) => ipcRenderer.invoke("review:saveSample", sample),
  loadReviewSamples: (limit = 50) => ipcRenderer.invoke("review:loadSamples", limit),
  loadScannerLearningRules: () => ipcRenderer.invoke("scanner:loadLearningRules"),
  saveScannerLearningRules: (rules: ScannerLearningRulePayload) => ipcRenderer.invoke("scanner:saveLearningRules", rules),
  loadArtifacts: () => ipcRenderer.invoke("artifacts:load"),
  saveArtifacts: (records: StoredArtifactRecord[]) => ipcRenderer.invoke("artifacts:saveMany", records),
  exportGood: (payload: GoodDatabase) => ipcRenderer.invoke("good:export", payload),
  publishScannerStatus: (status: ScannerStatusPayload) => ipcRenderer.invoke("scanner:publishStatus", status),
  showOverlay: () => ipcRenderer.invoke("overlay:show"),
  hideOverlay: () => ipcRenderer.invoke("overlay:hide"),
  onScannerCommand: (callback: (command: "start-auto" | "stop") => void) => {
    const listener = (_event: Electron.IpcRendererEvent, command: "start-auto" | "stop") => callback(command);
    ipcRenderer.on("scanner:command", listener);
    return () => ipcRenderer.removeListener("scanner:command", listener);
  },
});
