/**
 * Rig Integration Module for QwenClaw
 * 
 * Provides seamless integration between QwenClaw and Rig AI agent service
 */

import { RigClient } from "./client";

let rigClient: RigClient | null = null;

/**
 * Initialize Rig client
 */
export function initRigClient(host = "127.0.0.1", port = 8080): RigClient {
  rigClient = new RigClient({ host, port });
  return rigClient;
}

/**
 * Get Rig client instance
 */
export function getRigClient(): RigClient | null {
  return rigClient;
}

/**
 * Check if Rig service is available
 */
export async function isRigAvailable(): Promise<boolean> {
  if (!rigClient) return false;
  return await rigClient.health();
}

/**
 * Execute a prompt using Rig agent
 */
export async function executeWithRig(
  sessionId: string,
  prompt: string
): Promise<string> {
  if (!rigClient) {
    throw new Error("Rig client not initialized. Call initRigClient() first.");
  }

  return await rigClient.executePrompt(sessionId, prompt);
}

/**
 * Create a multi-agent council for complex tasks
 */
export async function createCouncil(
  name: string,
  agentConfigs: Array<{ name: string; preamble: string; model?: string }>
): Promise<string> {
  if (!rigClient) {
    throw new Error("Rig client not initialized. Call initRigClient() first.");
  }

  return await rigClient.createCouncil(name, agentConfigs);
}

/**
 * Execute task with agent council
 */
export async function executeWithCouncil(
  councilId: string,
  task: string
): Promise<string> {
  if (!rigClient) {
    throw new Error("Rig client not initialized. Call initRigClient() first.");
  }

  return await rigClient.executeCouncil(councilId, task);
}

/**
 * Search for relevant documents using RAG
 */
export async function searchDocuments(
  query: string,
  limit = 5
): Promise<Array<{ id: string; content: string; metadata: Record<string, unknown> }>> {
  if (!rigClient) {
    throw new Error("Rig client not initialized. Call initRigClient() first.");
  }

  return await rigClient.searchDocuments(query, limit);
}

/**
 * Add document to vector store for RAG
 */
export async function addDocumentToStore(
  content: string,
  metadata?: Record<string, unknown>
): Promise<string> {
  if (!rigClient) {
    throw new Error("Rig client not initialized. Call initRigClient() first.");
  }

  return await rigClient.addDocument(content, metadata);
}

/**
 * Search for relevant tools
 */
export async function searchTools(
  query: string,
  limit = 10
): Promise<Array<{ name: string; description: string; category: string }>> {
  if (!rigClient) {
    throw new Error("Rig client not initialized. Call initRigClient() first.");
  }

  return await rigClient.searchTools(query, limit);
}
