"use strict";
/**
 * AI Service for BFUI
 *
 * Integration with native_aijs SDK for AI capabilities
 */
Object.defineProperty(exports, "__esModule", { value: true });
exports.aiService = void 0;
const sdk_1 = require("@bluefly/native_aijs/sdk");
// Configure monitoring
const monitoring = sdk_1.MonitoringService.getInstance();
monitoring.startServer(3010);
// Initialize the SDK with default configuration
const sdk = new sdk_1.NativeAISDK({
    defaultProvider: 'anthropic',
    baseUrl: process.env.NATIVE_AI_API_URL || 'http://localhost:3001',
    apiKey: process.env.NATIVE_AI_API_KEY,
    monitoring: {
        enabled: true,
        serviceName: 'bfui',
        environment: process.env.NODE_ENV
    },
    caching: {
        enabled: true,
        ttl: 3600 // 1 hour
    },
    retry: {
        maxRetries: 3,
        initialDelay: 1000,
        maxDelay: 10000,
        factor: 2
    }
});
// Initialize BFUI-specific adapter
const bfuiAdapter = new sdk_1.BfuiAdapter(sdk);
/**
 * Convert BFUI chat request to native_aijs request format
 */
const convertToNativeRequest = (chatRequest) => {
    return {
        provider: chatRequest.provider,
        model: chatRequest.model,
        messages: chatRequest.messages.map(msg => ({
            role: msg.role,
            content: msg.content,
            name: msg.name
        })),
        parameters: {
            temperature: chatRequest.temperature || 0.7,
            max_tokens: chatRequest.maxTokens || 1000,
            stream: chatRequest.stream || false,
            system_prompt: chatRequest.systemPrompt
        },
        tools: chatRequest.functions ? chatRequest.functions.map(fn => ({
            name: fn.name,
            description: fn.description || '',
            parameters: fn.parameters
        })) : undefined
    };
};
/**
 * Convert native_aijs response to BFUI response format
 */
const convertToUIResponse = (response) => {
    return {
        id: response.id,
        model: response.model,
        created: Date.now(),
        choices: [
            {
                index: 0,
                message: {
                    role: 'assistant',
                    content: response.content
                },
                finish_reason: 'stop'
            }
        ],
        usage: response.usage
    };
};
/**
 * Convert native_aijs error to BFUI error format
 */
const convertError = (error) => {
    return {
        code: error.code,
        message: error.message,
        details: error.details
    };
};
/**
 * The AI service for BFUI
 */
exports.aiService = {
    /**
     * Execute a chat completion request
     */
    chat: async (chatRequest, options) => {
        try {
            const nativeRequest = convertToNativeRequest(chatRequest);
            // Configure retry options if provided
            const retryOptions = options?.retryCount ? {
                maxRetries: options.retryCount,
                initialDelay: options.retryDelay || 1000
            } : undefined;
            // Configure streaming if provided
            const streamCallback = options?.onStream ?
                (chunk) => options.onStream(chunk) :
                undefined;
            // Execute the request
            const response = await sdk.execute(nativeRequest, {
                retry: retryOptions,
                stream: streamCallback,
                abortSignal: options?.abortSignal
            });
            return convertToUIResponse(response);
        }
        catch (error) {
            // Convert and rethrow the error
            if (error instanceof sdk_1.NativeAISDKError) {
                throw convertError(error);
            }
            // Handle unexpected errors
            throw {
                code: 'unknown_error',
                message: error.message || 'An unexpected error occurred',
                details: error
            };
        }
    },
    /**
     * Generate embeddings for text
     */
    embeddings: async (texts, model) => {
        try {
            const request = {
                texts,
                model: model || 'text-embedding-ada-002'
            };
            const result = await sdk.embeddings(request);
            return result.embeddings;
        }
        catch (error) {
            if (error instanceof sdk_1.NativeAISDKError) {
                throw convertError(error);
            }
            throw {
                code: 'embedding_error',
                message: error.message || 'Failed to generate embeddings',
                details: error
            };
        }
    },
    /**
     * Generate RFP content using the BFUI adapter
     */
    generateRFPContent: async (rfpDocument, requirements) => {
        try {
            return await bfuiAdapter.generateRFPContent(rfpDocument, requirements);
        }
        catch (error) {
            if (error instanceof sdk_1.NativeAISDKError) {
                throw convertError(error);
            }
            throw {
                code: 'rfp_generation_error',
                message: error.message || 'Failed to generate RFP content',
                details: error
            };
        }
    },
    /**
     * Analyze document using the BFUI adapter
     */
    analyzeDocument: async (document, options) => {
        try {
            return await bfuiAdapter.analyzeDocument(document, options);
        }
        catch (error) {
            if (error instanceof sdk_1.NativeAISDKError) {
                throw convertError(error);
            }
            throw {
                code: 'document_analysis_error',
                message: error.message || 'Failed to analyze document',
                details: error
            };
        }
    },
    /**
     * Get monitoring metrics
     */
    getMetrics: () => {
        return monitoring.getMetrics();
    },
    /**
     * Reset SDK (mainly for testing)
     */
    resetSDK: () => {
        return sdk.reset();
    }
};
exports.default = exports.aiService;
//# sourceMappingURL=aiService.js.map