/**
 * TTS Tool Provider
 *
 * Unified provider for all TTS backends:
 * - Browser Web Speech API (no auth)
 * - AWS Polly (requires auth via server proxy)
 * - Google Cloud TTS (requires auth via server proxy)
 *
 * Part of PIE Assessment Toolkit.
 */
import { BrowserTTSProvider } from "../../services/tts/browser-provider.js";
/**
 * TTS Tool Provider
 *
 * Wraps TTS providers (Browser, Polly, Google) with the ToolProviderApi interface
 * for use in the ToolProviderRegistry.
 *
 * @example Browser TTS (no auth)
 * ```typescript
 * const provider = new TTSToolProvider();
 * await provider.initialize({ backend: 'browser' });
 * const ttsProvider = await provider.createInstance();
 * ```
 *
 * @example Server TTS (with auth)
 * ```typescript
 * const provider = new TTSToolProvider();
 * await provider.initialize({
 *   backend: 'polly',
 *   apiEndpoint: '/api/tts/synthesize',
 *   authToken: 'bearer-token', // Fetched via authFetcher
 * });
 * const ttsProvider = await provider.createInstance();
 * ```
 */
export class TTSToolProvider {
    providerId = "tts-service";
    providerName = "Text-to-Speech";
    category = "tts";
    version = "1.0";
    requiresAuth;
    ttsProvider = null;
    config = null;
    async emitTelemetry(eventName, payload) {
        try {
            await this.config?.onTelemetry?.(eventName, payload);
        }
        catch (error) {
            console.warn("[TTSToolProvider] telemetry callback failed:", error);
        }
    }
    /**
     * Create TTS tool provider
     *
     * @param backend TTS backend to use (default: 'browser')
     */
    constructor(backend = "browser") {
        this.requiresAuth = backend !== "browser";
    }
    /**
     * Initialize TTS provider
     *
     * Sets up the appropriate TTS backend.
     *
     * @param config Configuration with backend type and credentials
     * @throws Error if initialization fails or required config missing
     */
    async initialize(config) {
        if (this.ttsProvider) {
            console.warn("[TTSToolProvider] Already initialized, skipping reinitialization");
            return;
        }
        this.config = config;
        switch (config.backend) {
            case "browser":
                await this._initializeBrowserTTS(config);
                break;
            case "polly":
            case "google":
            case "server":
                await this._initializeServerTTS(config);
                break;
            default:
                throw new Error(`[TTSToolProvider] Unknown backend: ${config.backend}`);
        }
        console.log(`[TTSToolProvider] Initialized successfully (backend: ${config.backend})`);
    }
    /**
     * Initialize browser TTS (Web Speech API)
     */
    async _initializeBrowserTTS(config) {
        // Check if Web Speech API is available
        if (typeof window === "undefined" || !("speechSynthesis" in window)) {
            throw new Error("[TTSToolProvider] Browser TTS not supported (Web Speech API not available)");
        }
        this.ttsProvider = new BrowserTTSProvider();
        console.log("[TTSToolProvider] Browser TTS initialized (Web Speech API)");
    }
    /**
     * Initialize server-based TTS (Polly, Google)
     */
    async _initializeServerTTS(config) {
        if (!config.apiEndpoint) {
            throw new Error("[TTSToolProvider] apiEndpoint required for server-based TTS backends");
        }
        // Server backends are optional; load implementation only when requested.
        const moduleLoadStartedAt = Date.now();
        await this.emitTelemetry("pie-tool-library-load-start", {
            toolId: "textToSpeech",
            operation: "server-provider-module-import",
            backend: config.serverProvider || config.backend,
        });
        const serverModule = await (async () => {
            try {
                const loaded = (await import("@pie-players/tts-client-server"));
                await this.emitTelemetry("pie-tool-library-load-success", {
                    toolId: "textToSpeech",
                    operation: "server-provider-module-import",
                    backend: config.serverProvider || config.backend,
                    duration: Date.now() - moduleLoadStartedAt,
                });
                return loaded;
            }
            catch (error) {
                await this.emitTelemetry("pie-tool-library-load-error", {
                    toolId: "textToSpeech",
                    operation: "server-provider-module-import",
                    backend: config.serverProvider || config.backend,
                    duration: Date.now() - moduleLoadStartedAt,
                    errorType: "ToolLibraryLoadError",
                    message: error instanceof Error ? error.message : String(error),
                });
                throw error;
            }
        })();
        this.ttsProvider = new serverModule.ServerTTSProvider();
        console.log(`[TTSToolProvider] Server TTS initialized (provider: ${config.serverProvider || config.backend})`);
    }
    /**
     * Create a TTS provider instance
     *
     * Returns the initialized TTS provider.
     *
     * @param config Optional instance-specific configuration (currently unused)
     * @returns TTS provider
     * @throws Error if provider not initialized
     */
    async createInstance(config) {
        if (!this.ttsProvider) {
            throw new Error("[TTSToolProvider] Provider not initialized. Call initialize() first.");
        }
        return this.ttsProvider;
    }
    /**
     * Get provider capabilities
     *
     * @returns TTS capabilities based on backend
     */
    getCapabilities() {
        const isBrowser = this.config?.backend === "browser";
        return {
            supportsOffline: isBrowser,
            requiresAuth: !isBrowser,
            maxInstances: 1, // Single TTS instance (playback is sequential)
            features: {
                wordBoundary: true, // All backends support word highlighting
                pause: true,
                resume: true,
                rateControl: true,
                pitchControl: isBrowser, // Only browser supports pitch
                voiceSelection: true,
            },
        };
    }
    /**
     * Check if provider is ready
     *
     * @returns true if provider is initialized
     */
    isReady() {
        return this.ttsProvider !== null;
    }
    /**
     * Clean up provider resources
     *
     * Destroys the TTS provider and releases resources.
     */
    destroy() {
        if (this.ttsProvider) {
            this.ttsProvider.destroy();
            this.ttsProvider = null;
        }
        this.config = null;
        console.log("[TTSToolProvider] Destroyed");
    }
}
//# sourceMappingURL=TTSToolProvider.js.map