import { Message, MessageChunk } from '@axiom-lattice/protocols';

/**
 * Core types for the Axiom Lattice Client SDK
 */

/**
 * Transport method for client-server communication
 * Note: Currently only "ws" is used for tool registration
 */
type Transport = "sse" | "ws";
/**
 * Configuration options for the Client
 */
interface ClientConfig {
    /**
     * Base URL for the API
     */
    baseURL: string;
    /**
     * API key for authentication
     */
    apiKey: string;
    /**
     * Assistant identifier
     */
    assistantId: string;
    /**
     * Transport method (Server-Sent Events or WebSocket)
     */
    transport: Transport;
    /**
     * Request timeout in milliseconds (optional, defaults to 30000)
     */
    timeout?: number;
    /**
     * Additional headers to include in requests (optional)
     */
    headers?: Record<string, string>;
    /**
     * Configuration for retry behavior (optional)
     */
    retry?: RetryConfig;
}
/**
 * Configuration for retry behavior
 */
interface RetryConfig {
    /**
     * Maximum number of retry attempts
     */
    maxRetries: number;
    /**
     * Initial delay between retries in milliseconds
     */
    initialDelayMs: number;
    /**
     * Maximum delay between retries in milliseconds
     */
    maxDelayMs: number;
    /**
     * Factor to multiply delay by after each retry attempt
     */
    backoffFactor: number;
}
/**
 * Thread creation options
 */
interface CreateThreadOptions {
    /**
     * Optional metadata for the thread
     */
    metadata?: Record<string, any>;
}
/**
 * Thread information
 */
interface Thread {
    /**
     * Thread identifier
     */
    id: string;
    /**
     * Thread metadata
     */
    metadata?: Record<string, any>;
    /**
     * Thread creation timestamp
     */
    createdAt: string;
}
/**
 * Chat send options
 */
interface ChatSendOptions {
    /**
     * Thread identifier
     */
    threadId: string;
    /**
     * Messages to send
     */
    messages: Message[];
    /**
     * Files to attach (optional)
     */
    files?: any[];
    /**
     * Command to execute (optional)
     */
    command?: {
        resume?: {
            action: string;
            data: Record<string, any> & {
                config?: {
                    thread_id?: string;
                    work_log_id?: string;
                };
            };
            message: string;
        };
        update?: any;
        send?: {
            node: string;
            input: any;
        };
    };
    [key: string]: any;
}
/**
 * Chat stream options
 */
interface ChatStreamOptions extends ChatSendOptions {
    /**
     * Whether to run in background (optional)
     */
    background?: boolean;
    /**
     * Whether to return agent state when stream completes (optional)
     */
    enableReturnStateWhenSteamCompleted?: boolean;
}
/**
 * Stream callbacks interface
 */
interface StreamCallbacks {
    /**
     * Called when a stream event is received
     */
    onEvent: (event: MessageChunk) => void;
    /**
     * Called when the stream completes, with optional agent state
     */
    onComplete?: (state?: AgentState) => void;
    /**
     * Called when an error occurs
     */
    onError?: (error: Error) => void;
}
/**
 * Chat response
 */
interface ChatResponse {
    /**
     * Response messages
     */
    messages: Message[];
    /**
     * Trace ID for debugging
     */
    traceId?: string;
}
/**
 * Tool registration options
 */
interface RegisterToolOptions {
    /**
     * Tool name
     */
    name: string;
    /**
     * Tool parameter schema
     */
    schema: object;
    /**
     * Tool handler function
     */
    handler: (params: any) => Promise<any>;
}
/**
 * Get messages options
 */
interface GetMessagesOptions {
    /**
     * Thread identifier
     */
    threadId: string;
    /**
     * Maximum number of messages to return
     */
    limit?: number;
    /**
     * Message ID to start from (for pagination)
     */
    after?: string;
    /**
     * Whether to return messages in reverse chronological order
     */
    reverse?: boolean;
}
/**
 * Resume stream options
 */
interface ResumeStreamOptions {
    /**
     * Thread identifier
     */
    threadId: string;
    /**
     * Message identifier (usually run_id)
     */
    messageId: string;
    /**
     * Content already received (used to find resume position)
     */
    knownContent: string;
    /**
     * Polling interval in milliseconds (default: 100ms)
     */
    pollInterval?: number;
}
/**
 * Thread list options
 */
interface ListThreadsOptions {
    /**
     * Maximum number of threads to return
     */
    limit?: number;
    /**
     * Offset for pagination
     */
    offset?: number;
}
/**
 * Run options
 */
type RunOptions = {
    /**
     * Thread identifier
     */
    threadId: string;
    /**
     * Message to send
     */
    message: string;
    /**
     * Files to attach (optional)
     */
    files?: any[];
    /**
     * Command to execute (optional)
     */
    command?: any;
    /**
     * Whether to stream the response (optional)
     */
    streaming?: boolean;
    /**
     * Whether to run in background (optional)
     */
    background?: boolean;
    /**
     * Whether to return agent state when stream completes (optional)
     */
    enableReturnStateWhenSteamCompleted?: boolean;
} & Record<string, any>;
/**
 * Agent state
 */
interface AgentState {
    values: {
        messages: Message[];
        [key: string]: any;
    };
    tasks: Array<{
        interrupts: Array<{
            value: any;
        }>;
    }>;
}
/**
 * Custom error classes
 */
declare class ApiError extends Error {
    statusCode: number;
    responseBody?: any | undefined;
    constructor(message: string, statusCode: number, responseBody?: any | undefined);
}
declare class NetworkError extends Error {
    constructor(message: string);
}
declare class AuthenticationError extends Error {
    constructor(message: string);
}

/**
 * Abstract client class for interacting with the Axiom Lattice Agent Service API
 * Provides common functionality for different client implementations
 */
declare abstract class AbstractClient {
    protected config: ClientConfig;
    protected assistantId: string;
    protected tenantId: string;
    protected registeredTools: Map<string, RegisterToolOptions>;
    /**
     * Creates a new AbstractClient instance
     * @param config - Configuration options for the client
     */
    constructor(config: ClientConfig);
    /**
     * Set tenant ID for multi-tenant environments
     * @param tenantId - Tenant identifier
     */
    abstract setTenantId(tenantId: string): void;
    /**
     * Abstract method for making API requests
     * To be implemented by concrete client classes
     */
    protected abstract makeRequest<T>(url: string, options?: {
        method?: string;
        body?: any;
        headers?: Record<string, string>;
    }): Promise<T>;
    /**
     * Abstract method for streaming API requests
     * To be implemented by concrete client classes
     */
    /**
     * Helper method to build stream request parameters
     * @param options - Options for running the agent
     * @returns The formatted request parameters
     */
    protected buildStreamRequestParams(options: RunOptions): {
        url: string;
        method: string;
        body: any;
    };
    protected abstract streamRequest(options: RunOptions, onEvent: (event: MessageChunk) => void, onComplete?: (state?: AgentState) => void, onError?: (error: Error) => void): () => void;
    /**
     * Creates a new thread
     * @param options - Options for creating a thread
     * @returns A promise that resolves to the thread ID
     */
    createThread(options: CreateThreadOptions): Promise<string>;
    /**
     * Retrieves thread information
     * @param threadId - Thread identifier
     * @returns A promise that resolves to the thread information
     */
    getThread(threadId: string): Promise<Thread>;
    /**
     * Lists all threads
     * @param options - Options for listing threads
     * @returns A promise that resolves to an array of threads
     */
    listThreads(options?: ListThreadsOptions): Promise<Thread[]>;
    /**
     * Deletes a thread
     * @param threadId - Thread identifier
     * @returns A promise that resolves when the thread is deleted
     */
    deleteThread(threadId: string): Promise<void>;
    /**
     * Retrieves messages from a thread
     * @param options - Options for retrieving messages
     * @returns A promise that resolves to an array of messages
     */
    getMessages(options: GetMessagesOptions): Promise<Message[]>;
    /**
     * Retrieves agent state
     * @param threadId - Thread identifier
     * @returns A promise that resolves to the agent state
     */
    getAgentState(threadId: string): Promise<AgentState>;
    /**
     * Gets agent graph visualization
     * @returns A promise that resolves to the graph visualization data
     */
    getAgentGraph(): Promise<string>;
    /**
     * Run agent with options
     * @param options - Options for running the agent
     * @returns A promise that resolves to the run result
     */
    run(options: RunOptions): Promise<ChatResponse>;
    /**
     * Chat namespace for sending messages and streaming responses
     */
    chat: {
        /**
         * Sends a message to a thread and receives a response
         * @param options - Options for sending a message
         * @returns A promise that resolves to the chat response
         */
        send: (options: ChatSendOptions) => Promise<ChatResponse>;
        /**
         * Sends a message to a thread and streams the response
         * @param options - Options for streaming a message
         * @param onEvent - Callback function that receives stream events
         * @param onComplete - Optional callback function called when streaming completes
         * @param onError - Optional callback function called when an error occurs
         * @returns A function that can be called to stop the stream
         */
        stream: (options: ChatStreamOptions, onEvent: (event: MessageChunk) => void, onComplete?: (state?: AgentState) => void, onError?: (error: Error) => void) => (() => void);
    };
    /**
     * Resume streaming from a known position
     * @param options - Options for resuming the stream
     * @param onEvent - Callback function that receives stream events
     * @param onComplete - Optional callback function called when streaming completes
     * @param onError - Optional callback function called when an error occurs
     * @returns A function that can be called to stop the stream
     */
    abstract resumeStream(options: ResumeStreamOptions, onEvent: (event: MessageChunk) => void, onComplete?: () => void, onError?: (error: Error) => void): () => void;
    /**
     * Tools namespace for registering and unregistering client-side tools
     */
    tools: {
        /**
         * Registers a client-side tool
         * @param options - Options for registering a tool
         */
        register: (options: RegisterToolOptions) => void;
        /**
         * Unregisters a client-side tool
         * @param name - Tool name
         */
        unregister: (name: string) => void;
    };
}

/**
 * Web client class for interacting with the Axiom Lattice Agent Service API
 */
declare class Client extends AbstractClient {
    private headers;
    /**
     * Creates a new Client instance
     * @param config - Configuration options for the client
     */
    constructor(config: ClientConfig);
    /**
     * Helper method to handle fetch responses and errors
     * @private
     */
    private handleResponse;
    /**
     * Helper method to make fetch requests
     * @private
     */
    private fetchWithTimeout;
    /**
     * Set tenant ID for multi-tenant environments
     * @param tenantId - Tenant identifier
     */
    setTenantId(tenantId: string): void;
    /**
     * Implementation of the abstract makeRequest method for web clients
     * @param url - The URL to make the request to
     * @param options - Request options
     * @returns A promise that resolves to the response data
     */
    protected makeRequest<T>(url: string, options?: {
        method?: string;
        body?: any;
        headers?: Record<string, string>;
    }): Promise<T>;
    /**
     * Implementation of the abstract streamRequest method for web clients
     */
    protected streamRequest(options: RunOptions, onEvent: (event: MessageChunk) => void, onComplete?: (state?: AgentState) => void, onError?: (error: Error) => void): () => void;
    /**
     * Resume streaming from a known position
     * @param options - Options for resuming the stream
     * @param onEvent - Callback function that receives stream events
     * @param onComplete - Optional callback function called when streaming completes
     * @param onError - Optional callback function called when an error occurs
     * @returns A function that can be called to stop the stream
     */
    resumeStream(options: ResumeStreamOptions, onEvent: (event: MessageChunk) => void, onComplete?: () => void, onError?: (error: Error) => void): () => void;
    /**
     * Stream run results
     * @param options - Options for streaming run results
     * @param onEvent - Callback function that receives stream events
     * @param onComplete - Optional callback function called when streaming completes
     * @param onError - Optional callback function called when an error occurs
     * @returns A function that can be called to stop the stream
     */
    private streamRun;
}

/**
 * WeChat Mini Program client for interacting with the Axiom Lattice Agent Service API
 */
declare class WeChatClient extends AbstractClient {
    /**
     * Creates a new WeChatClient instance
     * @param config - Configuration options for the client
     */
    constructor(config: ClientConfig);
    /**
     * Set tenant ID for multi-tenant environments
     * @param tenantId - Tenant identifier
     */
    setTenantId(tenantId: string): void;
    /**
     * Implementation of the abstract makeRequest method for WeChat clients
     * @param url - The URL to make the request to
     * @param options - Request options
     * @returns A promise that resolves to the response data
     */
    protected makeRequest<T>(url: string, options?: {
        method?: string;
        body?: any;
        headers?: Record<string, string>;
    }): Promise<T>;
    /**
     * Implementation of the abstract streamRequest method for WeChat clients
     */
    protected streamRequest(options: RunOptions, onEvent: (event: MessageChunk) => void, onComplete?: (state?: AgentState) => void, onError?: (error: Error) => void): () => void;
    /**
     * Resume streaming from a known position
     * @param options - Options for resuming the stream
     * @param onEvent - Callback function that receives stream events
     * @param onComplete - Optional callback function called when streaming completes
     * @param onError - Optional callback function called when an error occurs
     * @returns A function that can be called to stop the stream
     */
    resumeStream(options: ResumeStreamOptions, onEvent: (event: MessageChunk) => void, onComplete?: () => void, onError?: (error: Error) => void): () => void;
    /**
     * Helper method to make WeChat HTTP requests
     * @private
     */
    private request;
    /**
     * Stream run results using WeChat's downloadFile API
     * @param options - Options for streaming run results
     * @param onEvent - Callback function that receives stream events
     * @param onComplete - Optional callback function called when streaming completes
     * @param onError - Optional callback function called when an error occurs
     * @returns A function that can be called to stop the stream
     */
    private streamRun;
    decodeUint8Array(uint8Array: ArrayBuffer): any;
    buf2hex(arrayBuffer: ArrayBuffer): string;
    /**
     * Convert hexadecimal string to text (supports Chinese characters)
     * @param {String} hex - Hexadecimal string
     * @return {String} Decoded string including Chinese characters
     */
    hexToStr(hex: string): any;
}

/**
 * ChunkMessageMerger
 *
 * A utility for handling streaming message chunks and merging them into complete messages.
 */

/**
 * Creates a simple message merger for handling streaming message chunks
 * @returns An object with methods to push chunks and retrieve merged messages
 */
declare function createSimpleMessageMerger(): {
    push: (chunk: MessageChunk) => void;
    initialMessages: (msgs: any[]) => void;
    getMessages: () => any[];
    getMessagesWithoutToolCalls: () => any[];
    reset: () => void;
};

export { AbstractClient, AgentState, ApiError, AuthenticationError, ChatResponse, ChatSendOptions, ChatStreamOptions, Client, ClientConfig, CreateThreadOptions, GetMessagesOptions, ListThreadsOptions, NetworkError, RegisterToolOptions, ResumeStreamOptions, RetryConfig, RunOptions, StreamCallbacks, Thread, Transport, WeChatClient, createSimpleMessageMerger };
