"use strict";
/**
 * UI Configuration Service
 * Real configuration management for UI components
 */
Object.defineProperty(exports, "__esModule", { value: true });
exports.uiConfigService = exports.UIConfigService = void 0;
class UIConfigService {
    constructor() {
        this.watchers = [];
        this.config = this.loadConfiguration();
        this.setupConfigWatching();
    }
    /**
     * Load configuration from multiple sources
     */
    loadConfiguration() {
        // Default configuration
        const defaultConfig = {
            chat: {
                welcomeMessages: [
                    "Hello! I'm your AI assistant. How can I help you today?",
                    "Welcome! I'm here to help with any questions or tasks you have.",
                    "Hi there! What would you like to explore together?",
                    "Greetings! I'm ready to assist you with information, analysis, or creative tasks."
                ],
                placeholderTexts: [
                    "Ask me anything...",
                    "What would you like to know?",
                    "Type your message here...",
                    "How can I help you today?"
                ],
                systemMessages: {
                    connecting: "Connecting to AI service...",
                    error: "I'm having trouble connecting right now. Please try again in a moment.",
                    rateLimit: "I'm receiving a lot of requests right now. Please wait a moment before sending another message.",
                    noModels: "No AI models are currently available. Please check your configuration."
                },
                suggestions: [
                    "Explain a complex topic",
                    "Help me write something",
                    "Analyze this data",
                    "Brainstorm ideas",
                    "Review my code",
                    "Summarize information"
                ]
            },
            models: {
                defaultModel: 'gpt-4',
                preferredModels: ['gpt-4', 'gpt-3.5-turbo', 'claude-3-sonnet'],
                modelDisplayNames: {
                    'gpt-4': 'GPT-4 (Most Capable)',
                    'gpt-4-turbo': 'GPT-4 Turbo (Fast & Capable)',
                    'gpt-3.5-turbo': 'GPT-3.5 Turbo (Fast & Efficient)',
                    'claude-3-opus': 'Claude 3 Opus (Advanced Reasoning)',
                    'claude-3-sonnet': 'Claude 3 Sonnet (Balanced)',
                    'claude-3-haiku': 'Claude 3 Haiku (Fast)',
                    'apple-intelligence': 'Apple Intelligence (Private)'
                }
            },
            themes: {
                default: 'auto',
                customThemes: {}
            },
            features: {
                enableVoiceInput: false,
                enableFileUpload: false,
                enableMarkdown: true,
                enableCodeHighlighting: true,
                enableStreaming: true,
                maxHistoryLength: 50
            },
            accessibility: {
                announceMessages: false,
                highContrast: false,
                reducedMotion: false,
                fontSize: 'medium'
            },
            branding: {
                appName: 'LLM Platform',
                primaryColor: '#3B82F6',
                secondaryColor: '#8B5CF6'
            }
        };
        try {
            // Load from environment variables
            const envConfig = this.loadFromEnvironment();
            // Load from local storage (user preferences)
            const localConfig = this.loadFromLocalStorage();
            // Load from remote API if available
            const remoteConfig = this.loadFromRemoteAPI();
            // Merge configurations (environment > remote > local > default)
            return this.mergeConfigs(defaultConfig, localConfig, remoteConfig, envConfig);
        }
        catch (error) {
            console.warn('Failed to load UI configuration, using defaults:', error);
            return defaultConfig;
        }
    }
    /**
     * Load configuration from environment variables
     */
    loadFromEnvironment() {
        const config = {};
        // Chat configuration
        if (process.env.REACT_APP_WELCOME_MESSAGE) {
            config.chat = {
                ...config.chat,
                welcomeMessages: [process.env.REACT_APP_WELCOME_MESSAGE]
            };
        }
        if (process.env.REACT_APP_PLACEHOLDER_TEXT) {
            config.chat = {
                ...config.chat,
                placeholderTexts: [process.env.REACT_APP_PLACEHOLDER_TEXT]
            };
        }
        // Model configuration
        if (process.env.REACT_APP_DEFAULT_MODEL) {
            config.models = {
                ...config.models,
                defaultModel: process.env.REACT_APP_DEFAULT_MODEL
            };
        }
        // Feature flags
        if (process.env.REACT_APP_ENABLE_VOICE_INPUT) {
            config.features = {
                ...config.features,
                enableVoiceInput: process.env.REACT_APP_ENABLE_VOICE_INPUT === 'true'
            };
        }
        if (process.env.REACT_APP_ENABLE_FILE_UPLOAD) {
            config.features = {
                ...config.features,
                enableFileUpload: process.env.REACT_APP_ENABLE_FILE_UPLOAD === 'true'
            };
        }
        if (process.env.REACT_APP_ENABLE_STREAMING) {
            config.features = {
                ...config.features,
                enableStreaming: process.env.REACT_APP_ENABLE_STREAMING === 'true'
            };
        }
        // Branding
        if (process.env.REACT_APP_BRAND_NAME) {
            config.branding = {
                ...config.branding,
                appName: process.env.REACT_APP_BRAND_NAME
            };
        }
        if (process.env.REACT_APP_BRAND_COLOR) {
            config.branding = {
                ...config.branding,
                primaryColor: process.env.REACT_APP_BRAND_COLOR
            };
        }
        return config;
    }
    /**
     * Load configuration from local storage
     */
    loadFromLocalStorage() {
        try {
            const stored = localStorage.getItem('llm-ui-config');
            if (stored) {
                return JSON.parse(stored);
            }
        }
        catch (error) {
            console.warn('Failed to load configuration from localStorage:', error);
        }
        return {};
    }
    /**
     * Load configuration from remote API
     */
    async loadFromRemoteAPI() {
        const apiUrl = process.env.REACT_APP_CONFIG_API_URL;
        if (!apiUrl) {
            return {};
        }
        try {
            const response = await fetch(`${apiUrl}/ui-config`, {
                headers: {
                    'Accept': 'application/json'
                },
                timeout: 5000
            });
            if (response.ok) {
                const config = await response.json();
                console.log('Loaded UI configuration from API');
                return config;
            }
        }
        catch (error) {
            console.warn('Failed to load configuration from API:', error);
        }
        return {};
    }
    /**
     * Merge configuration objects
     */
    mergeConfigs(...configs) {
        return configs.reduce((acc, config) => {
            return this.deepMerge(acc, config);
        }, {});
    }
    /**
     * Deep merge utility
     */
    deepMerge(target, source) {
        const output = Object.assign({}, target);
        if (this.isObject(target) && this.isObject(source)) {
            Object.keys(source).forEach(key => {
                if (this.isObject(source[key])) {
                    if (!(key in target)) {
                        Object.assign(output, { [key]: source[key] });
                    }
                    else {
                        output[key] = this.deepMerge(target[key], source[key]);
                    }
                }
                else {
                    Object.assign(output, { [key]: source[key] });
                }
            });
        }
        return output;
    }
    isObject(item) {
        return item && typeof item === 'object' && !Array.isArray(item);
    }
    /**
     * Setup configuration watching
     */
    setupConfigWatching() {
        // Watch for localStorage changes
        window.addEventListener('storage', (event) => {
            if (event.key === 'llm-ui-config') {
                this.config = this.loadConfiguration();
                this.notifyWatchers();
            }
        });
        // Watch for system theme changes
        const mediaQuery = window.matchMedia('(prefers-color-scheme: dark)');
        mediaQuery.addEventListener('change', () => {
            if (this.config.themes.default === 'auto') {
                this.notifyWatchers();
            }
        });
    }
    /**
     * Notify configuration watchers
     */
    notifyWatchers() {
        this.watchers.forEach(callback => {
            try {
                callback(this.config);
            }
            catch (error) {
                console.error('Error in configuration watcher:', error);
            }
        });
    }
    /**
     * Get current configuration
     */
    getConfig() {
        return this.config;
    }
    /**
     * Get random welcome message
     */
    getWelcomeMessage() {
        const messages = this.config.chat.welcomeMessages;
        return messages[Math.floor(Math.random() * messages.length)];
    }
    /**
     * Get random placeholder text
     */
    getPlaceholderText() {
        const texts = this.config.chat.placeholderTexts;
        return texts[Math.floor(Math.random() * texts.length)];
    }
    /**
     * Get model display name
     */
    getModelDisplayName(modelId) {
        return this.config.models.modelDisplayNames[modelId] || modelId;
    }
    /**
     * Get system message
     */
    getSystemMessage(type) {
        return this.config.chat.systemMessages[type];
    }
    /**
     * Get suggestions for the current context
     */
    getSuggestions(context) {
        // In the future, this could be context-aware
        return this.config.chat.suggestions;
    }
    /**
     * Check if feature is enabled
     */
    isFeatureEnabled(feature) {
        return this.config.features[feature];
    }
    /**
     * Get accessibility settings
     */
    getAccessibilitySettings() {
        return this.config.accessibility;
    }
    /**
     * Get branding settings
     */
    getBrandingSettings() {
        return this.config.branding;
    }
    /**
     * Update configuration
     */
    updateConfig(updates) {
        this.config = this.deepMerge(this.config, updates);
        // Save to localStorage
        try {
            localStorage.setItem('llm-ui-config', JSON.stringify(updates));
        }
        catch (error) {
            console.warn('Failed to save configuration to localStorage:', error);
        }
        this.notifyWatchers();
    }
    /**
     * Update user preferences
     */
    updateUserPreferences(preferences) {
        const updates = {};
        if (preferences.theme) {
            updates.themes = { ...this.config.themes, default: preferences.theme };
        }
        if (preferences.fontSize) {
            updates.accessibility = {
                ...this.config.accessibility,
                fontSize: preferences.fontSize
            };
        }
        if (preferences.enableVoiceInput !== undefined) {
            updates.features = {
                ...this.config.features,
                enableVoiceInput: preferences.enableVoiceInput
            };
        }
        if (preferences.enableFileUpload !== undefined) {
            updates.features = {
                ...this.config.features,
                enableFileUpload: preferences.enableFileUpload
            };
        }
        if (preferences.preferredModel) {
            updates.models = {
                ...this.config.models,
                defaultModel: preferences.preferredModel
            };
        }
        this.updateConfig(updates);
    }
    /**
     * Watch for configuration changes
     */
    onConfigChange(callback) {
        this.watchers.push(callback);
        // Return unsubscribe function
        return () => {
            const index = this.watchers.indexOf(callback);
            if (index > -1) {
                this.watchers.splice(index, 1);
            }
        };
    }
    /**
     * Reset to default configuration
     */
    resetToDefaults() {
        localStorage.removeItem('llm-ui-config');
        this.config = this.loadConfiguration();
        this.notifyWatchers();
    }
    /**
     * Get configuration for specific component
     */
    getComponentConfig(component) {
        return this.config[component];
    }
    /**
     * Export configuration for backup
     */
    exportConfig() {
        return JSON.stringify(this.config, null, 2);
    }
    /**
     * Import configuration from backup
     */
    importConfig(configString) {
        try {
            const importedConfig = JSON.parse(configString);
            this.updateConfig(importedConfig);
        }
        catch (error) {
            throw new Error('Invalid configuration format');
        }
    }
}
exports.UIConfigService = UIConfigService;
// Export singleton instance
exports.uiConfigService = new UIConfigService();
exports.default = exports.uiConfigService;
//# sourceMappingURL=UIConfigService.js.map