import { ipcMain } from "electron";
import { SmartContextStore } from "../utils/smart_context_store";
import type {
  SmartContextRequest,
  SmartContextResponse,
  UpdateSmartContextParams,
} from "../ipc_types";

const smartContextStore = new SmartContextStore();

export function registerSmartContextHandlers() {
  // Get smart context for a chat
  ipcMain.handle("smart-context:get", async (event, params: SmartContextRequest) => {
    try {
      const context = await smartContextStore.getContext(params);
      return { success: true, context };
    } catch (error) {
      throw new Error(`Failed to get smart context: ${error}`);
    }
  });

  // Update smart context
  ipcMain.handle("smart-context:update", async (event, params: UpdateSmartContextParams) => {
    try {
      await smartContextStore.updateContext(params);
      return { success: true };
    } catch (error) {
      throw new Error(`Failed to update smart context: ${error}`);
    }
  });

  // Clear smart context
  ipcMain.handle("smart-context:clear", async (event, params: { chatId: number }) => {
    try {
      await smartContextStore.clearContext(params.chatId);
      return { success: true };
    } catch (error) {
      throw new Error(`Failed to clear smart context: ${error}`);
    }
  });

  // Get context statistics
  ipcMain.handle("smart-context:stats", async (event, params: { chatId: number }) => {
    try {
      const stats = await smartContextStore.getContextStats(params.chatId);
      return { success: true, stats };
    } catch (error) {
      throw new Error(`Failed to get context stats: ${error}`);
    }
  });
}
