"use strict";
/**
 * useAI Hook
 *
 * A React hook that provides access to AI capabilities from the native_aijs SDK
 */
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.useAI = void 0;
const react_1 = require("react");
const aiService_js_1 = __importDefault(require("../services/aiService.js"));
/**
 * Hook for using AI capabilities in React components
 */
const useAI = (options = {}) => {
    // State for tracking the current operation
    const [state, setState] = (0, react_1.useState)({
        status: AiOperationStatus.IDLE,
        error: null,
        messages: [],
        response: null,
    });
    // Reference to the abort controller for cancellation
    const abortControllerRef = (0, react_1.useRef)(null);
    // Default configuration
    const defaultConfig = {
        provider: 'anthropic',
        model: 'claude-3-haiku-20240307',
        temperature: 0.7,
        stream: false,
        ...options.initialConfig
    };
    /**
     * Send a chat request to the AI
     */
    const chat = (0, react_1.useCallback)(async (request, abortSignal) => {
        try {
            // Set loading state
            setState(prev => ({
                ...prev,
                status: request.stream ? AiOperationStatus.STREAMING : AiOperationStatus.LOADING,
                error: null
            }));
            // Create abort controller
            abortControllerRef.current = new AbortController();
            const signal = abortSignal || abortControllerRef.current.signal;
            // Prepare the full request with defaults
            const fullRequest = {
                ...defaultConfig,
                ...request,
            };
            // Update messages in state
            setState(prev => ({
                ...prev,
                messages: [...fullRequest.messages]
            }));
            // Track chunks if streaming
            const chunks = [];
            // Execute the request
            const response = await aiService_js_1.default.chat(fullRequest, {
                abortSignal: signal,
                onStream: request.stream ? (chunk) => {
                    // Handle streaming response
                    if (chunk.choices && chunk.choices[0]?.delta?.content) {
                        const content = chunk.choices[0].delta.content;
                        chunks.push({
                            role: 'assistant',
                            content
                        });
                        setState(prev => ({
                            ...prev,
                            status: AiOperationStatus.STREAMING,
                        }));
                    }
                } : undefined
            });
            // Add response message to messages array
            const responseMessage = response.choices[0].message;
            const updatedMessages = [...fullRequest.messages, responseMessage];
            // Update state with success
            setState({
                status: AiOperationStatus.SUCCESS,
                error: null,
                messages: updatedMessages,
                response
            });
            return {
                response,
                messages: updatedMessages
            };
        }
        catch (error) {
            // Handle errors
            const aiError = error;
            setState(prev => ({
                ...prev,
                status: AiOperationStatus.ERROR,
                error: aiError
            }));
            // Call error handler if provided
            if (options.onError) {
                options.onError(aiError);
            }
            throw aiError;
        }
        finally {
            // Clean up abort controller
            abortControllerRef.current = null;
        }
    }, [defaultConfig, options.onError]);
    /**
     * Generate embeddings for text
     */
    const generateEmbeddings = (0, react_1.useCallback)(async (texts, model) => {
        try {
            return await aiService_js_1.default.embeddings(texts, model);
        }
        catch (error) {
            const aiError = error;
            // Call error handler if provided
            if (options.onError) {
                options.onError(aiError);
            }
            throw aiError;
        }
    }, [options.onError]);
    /**
     * Analyze a document using the AI
     */
    const analyzeDocument = (0, react_1.useCallback)(async (document, options) => {
        try {
            setState(prev => ({
                ...prev,
                status: AiOperationStatus.LOADING,
                error: null
            }));
            const result = await aiService_js_1.default.analyzeDocument(document, options);
            setState(prev => ({
                ...prev,
                status: AiOperationStatus.SUCCESS
            }));
            return result;
        }
        catch (error) {
            const aiError = error;
            setState(prev => ({
                ...prev,
                status: AiOperationStatus.ERROR,
                error: aiError
            }));
            // Call error handler if provided
            if (options.onError) {
                options.onError(aiError);
            }
            throw aiError;
        }
    }, [options.onError]);
    /**
     * Cancel the current AI operation
     */
    const cancel = (0, react_1.useCallback)(() => {
        if (abortControllerRef.current) {
            abortControllerRef.current.abort();
            abortControllerRef.current = null;
            setState(prev => ({
                ...prev,
                status: AiOperationStatus.IDLE
            }));
        }
    }, []);
    /**
     * Reset the AI state
     */
    const reset = (0, react_1.useCallback)(() => {
        setState({
            status: AiOperationStatus.IDLE,
            error: null,
            messages: [],
            response: null
        });
    }, []);
    // Return the hook API
    return {
        // State
        state,
        status: state.status,
        messages: state.messages,
        response: state.response,
        error: state.error,
        isLoading: state.status === AiOperationStatus.LOADING,
        isStreaming: state.status === AiOperationStatus.STREAMING,
        isIdle: state.status === AiOperationStatus.IDLE,
        isError: state.status === AiOperationStatus.ERROR,
        isSuccess: state.status === AiOperationStatus.SUCCESS,
        // Actions
        chat,
        generateEmbeddings,
        analyzeDocument,
        cancel,
        reset,
        // Configuration
        defaultConfig
    };
};
exports.useAI = useAI;
exports.default = exports.useAI;
//# sourceMappingURL=useAI.js.map