"use strict";
/**
 * Native AI Plugin System Integration for BFUI
 *
 * This module provides integration between the Native AI plugin system
 * and the BFUI component library.
 */
Object.defineProperty(exports, "__esModule", { value: true });
exports.pluginManager = exports.BaseProviderAdapter = exports.BFUIPluginManager = exports.BFUIPluginConfigSchema = void 0;
const eventemitter3_1 = require("eventemitter3");
const zod_1 = require("zod");
// Import types from the plugin system
const plugins_1 = require("@bluefly/native_aijs/plugins");
/**
 * Schema for validating BFUI plugin configuration
 */
exports.BFUIPluginConfigSchema = zod_1.z.object({
    apiUrl: zod_1.z.string().url().optional(),
    apiKey: zod_1.z.string().optional(),
    defaultProvider: zod_1.z.string().optional(),
    monitoring: zod_1.z.object({
        enabled: zod_1.z.boolean(),
        serviceName: zod_1.z.string().optional(),
        environment: zod_1.z.string().optional()
    }).optional(),
    caching: zod_1.z.object({
        enabled: zod_1.z.boolean(),
        ttl: zod_1.z.number().optional()
    }).optional(),
    retry: zod_1.z.object({
        maxRetries: zod_1.z.number().optional(),
        initialDelay: zod_1.z.number().optional(),
        maxDelay: zod_1.z.number().optional(),
        factor: zod_1.z.number().optional()
    }).optional(),
    plugins: zod_1.z.record(zod_1.z.any()).optional()
});
/**
 * BFUI Plugin Manager
 *
 * This class manages the integration between BFUI and the Native AI plugin system.
 * It provides a simplified interface for BFUI components to use plugins.
 */
class BFUIPluginManager {
    /**
     * Private constructor for singleton pattern
     */
    constructor(config) {
        this.initialized = false;
        this.config = exports.BFUIPluginConfigSchema.parse(config);
        this.events = new eventemitter3_1.EventEmitter();
        this.logger = console;
        // Create plugin registry
        this.registry = new plugins_1.PluginRegistry();
    }
    /**
     * Get the singleton instance of the plugin manager
     */
    static getInstance(config) {
        if (!BFUIPluginManager._instance) {
            if (!config) {
                throw new Error('Plugin manager not initialized. Provide config on first call.');
            }
            BFUIPluginManager._instance = new BFUIPluginManager(config);
        }
        else if (config) {
            BFUIPluginManager._instance.config = exports.BFUIPluginConfigSchema.parse(config);
        }
        return BFUIPluginManager._instance;
    }
    /**
     * Initialize the plugin manager and all registered plugins
     */
    async initialize() {
        if (this.initialized) {
            this.logger.warn('Plugin manager already initialized');
            return;
        }
        this.logger.info('Initializing BFUI plugin manager');
        try {
            // Initialize the plugin registry
            const pluginContext = {
                registry: this.registry,
                config: this.config.plugins || {},
                events: this.events,
                logger: this.logger,
                services: {}
            };
            // Initialize all registered plugins
            for (const plugin of this.registry.getAllPlugins()) {
                try {
                    await plugin.initialize(pluginContext);
                    this.logger.info(`Initialized plugin: ${plugin.id}`);
                }
                catch (error) {
                    this.logger.error(`Failed to initialize plugin: ${plugin.id}`, error);
                }
            }
            this.initialized = true;
            this.logger.info('BFUI plugin manager initialized');
        }
        catch (error) {
            this.logger.error('Failed to initialize BFUI plugin manager', error);
            throw error;
        }
    }
    /**
     * Shut down the plugin manager and all registered plugins
     */
    async shutdown() {
        if (!this.initialized) {
            this.logger.warn('Plugin manager not initialized');
            return;
        }
        this.logger.info('Shutting down BFUI plugin manager');
        try {
            // Shut down all registered plugins
            for (const plugin of this.registry.getAllPlugins()) {
                try {
                    await plugin.shutdown();
                    this.logger.info(`Shut down plugin: ${plugin.id}`);
                }
                catch (error) {
                    this.logger.error(`Failed to shut down plugin: ${plugin.id}`, error);
                }
            }
            this.initialized = false;
            this.logger.info('BFUI plugin manager shut down');
        }
        catch (error) {
            this.logger.error('Failed to shut down BFUI plugin manager', error);
            throw error;
        }
    }
    /**
     * Register a plugin with the system
     */
    registerPlugin(plugin) {
        this.registry.register(plugin);
        // If already initialized, initialize this plugin immediately
        if (this.initialized) {
            const pluginContext = {
                registry: this.registry,
                config: this.config.plugins?.[plugin.id] || {},
                events: this.events,
                logger: this.logger,
                services: {}
            };
            plugin.initialize(pluginContext).catch(error => {
                this.logger.error(`Failed to initialize plugin: ${plugin.id}`, error);
            });
        }
    }
    /**
     * Unregister a plugin from the system
     */
    unregisterPlugin(pluginId) {
        this.registry.unregister(pluginId);
    }
    /**
     * Get a plugin by ID
     */
    getPlugin(pluginId) {
        return this.registry.getPlugin(pluginId);
    }
    /**
     * Get all plugins of a specific type
     */
    getPluginsByType(type) {
        return this.registry.getPluginsByType(type);
    }
    /**
     * Get all provider plugins
     */
    getProviderPlugins() {
        return this.registry.getPluginsByType('provider');
    }
    /**
     * Get a provider plugin by ID
     */
    getProviderPlugin(id) {
        const plugin = this.registry.getPlugin(id);
        if (plugin && plugin.type === 'provider') {
            return plugin;
        }
        return undefined;
    }
    /**
     * Get the default provider plugin
     */
    getDefaultProvider() {
        if (!this.config.defaultProvider) {
            return undefined;
        }
        return this.getProviderPlugin(this.config.defaultProvider);
    }
    /**
     * Check if the plugin manager is initialized
     */
    isInitialized() {
        return this.initialized;
    }
    /**
     * Get all registered plugins
     */
    getAllPlugins() {
        return this.registry.getAllPlugins();
    }
    /**
     * Subscribe to plugin events
     */
    on(event, listener) {
        this.events.on(event, listener);
    }
    /**
     * Unsubscribe from plugin events
     */
    off(event, listener) {
        this.events.off(event, listener);
    }
    /**
     * Emit a plugin event
     */
    emit(event, ...args) {
        this.events.emit(event, ...args);
    }
}
exports.BFUIPluginManager = BFUIPluginManager;
/**
 * Base Provider Adapter implementation
 */
class BaseProviderAdapter {
}
exports.BaseProviderAdapter = BaseProviderAdapter;
// Export singleton instance
exports.pluginManager = BFUIPluginManager.getInstance({
    apiUrl: process.env['NATIVE_AI_API_URL'] || 'http://localhost:3001',
    apiKey: process.env['NATIVE_AI_API_KEY'],
    defaultProvider: 'anthropic',
    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
    }
});
//# sourceMappingURL=plugin-system.js.map