import { jsx as _jsx } from "react/jsx-runtime";
import { createContext, useContext, useMemo, useCallback } from 'react';
import { useLocalStorageState } from '../hooks/useLocalStorage';
const DEFAULT_PROMPT = 'You are the AI assistant for model-context-playground.com.';
const DEFAULT_ATTACHMENT_CALLBACK_SOURCE = `async (attachment) => {
  // Optionally upload the attachment somewhere and return a sourceUrl
  // See the readme for details.
  console.info('Attachment cached. Customize this handler to upload files.', attachment)
  // const resp = await fetch('https://foo.bar/api', {
  //  method: 'POST',
  //  headers: {
  //    'x-api-key': 'xxxxx'
  //  },
  //  body: JSON.stringify(attachment)
  // })
  // return resp.json()
}`;
const ChatSettingsContext = createContext(undefined);
export const ChatSettingsProvider = ({ children, attachmentCallback, systemPrompt }) => {
    const { value: storedPrompt, setValue: setPromptValue, reset: resetPrompt } = useLocalStorageState('chat-agent-prompt', DEFAULT_PROMPT);
    const { value: storedAttachmentCallbackSource, setValue: setAttachmentCallbackValue, reset: resetAttachmentCallback } = useLocalStorageState('chat-attachment-callback-source', DEFAULT_ATTACHMENT_CALLBACK_SOURCE);
    const hasPromptOverride = systemPrompt !== undefined;
    const setAgentPrompt = useCallback((value) => {
        if (hasPromptOverride) {
            return;
        }
        setPromptValue(value);
    }, [hasPromptOverride, setPromptValue]);
    const resetAgentPrompt = useCallback(() => {
        if (hasPromptOverride) {
            return;
        }
        resetPrompt();
    }, [hasPromptOverride, resetPrompt]);
    const setAttachmentCallbackSource = useCallback((value) => {
        setAttachmentCallbackValue(value);
    }, [setAttachmentCallbackValue]);
    const attachmentCallbackEvaluation = useMemo(() => {
        const trimmed = storedAttachmentCallbackSource.trim();
        if (trimmed.length === 0) {
            return { callback: undefined, error: null };
        }
        try {
            const factory = new Function('"use strict"; return (' + trimmed + ');');
            const candidate = factory();
            if (typeof candidate !== 'function') {
                return { callback: undefined, error: 'Attachment handler must evaluate to a function.' };
            }
            const normalized = async (attachment) => {
                return await candidate(attachment);
            };
            return { callback: normalized, error: null };
        }
        catch (error) {
            const message = error instanceof Error ? error.message : 'Failed to evaluate attachment handler.';
            console.error('Error evaluating attachment handler from settings:', error);
            return { callback: undefined, error: message };
        }
    }, [storedAttachmentCallbackSource]);
    const hasAttachmentOverride = typeof attachmentCallback === 'function';
    const resolvedPrompt = hasPromptOverride ? systemPrompt ?? '' : storedPrompt;
    const contextValue = useMemo(() => ({
        agentPrompt: resolvedPrompt,
        setAgentPrompt,
        resetAgentPrompt,
        attachmentCallbackSource: storedAttachmentCallbackSource,
        setAttachmentCallbackSource,
        resetAttachmentCallbackSource: resetAttachmentCallback,
        attachmentCallback: attachmentCallback ?? attachmentCallbackEvaluation.callback,
        attachmentCallbackError: attachmentCallback ? null : attachmentCallbackEvaluation.error,
        isAgentPromptOverridden: hasPromptOverride,
        isAttachmentCallbackOverridden: hasAttachmentOverride
    }), [
        resolvedPrompt,
        setAgentPrompt,
        resetAgentPrompt,
        storedAttachmentCallbackSource,
        setAttachmentCallbackSource,
        resetAttachmentCallback,
        attachmentCallback,
        attachmentCallbackEvaluation,
        hasPromptOverride,
        hasAttachmentOverride
    ]);
    return (_jsx(ChatSettingsContext.Provider, { value: contextValue, children: children }));
};
export const useChatSettings = () => {
    const context = useContext(ChatSettingsContext);
    if (!context) {
        throw new Error('useChatSettings must be used within a ChatSettingsProvider');
    }
    return context;
};
