/**
 * @license
 * Copyright 2025 OElite Platform
 * SPDX-License-Identifier: Apache-2.0
 */
import { BaseProvider } from './baseProvider.js';
import { ProviderType } from './types.js';
import { OPENAI_MODELS } from './modelCatalog.js';
/**
 * Azure OpenAI provider implementation
 * Supports OpenAI models via Microsoft Azure
 */
export class AzureProvider extends BaseProvider {
    static DEFAULT_API_VERSION = '2024-02-15-preview';
    constructor(config) {
        super({
            ...config,
            type: ProviderType.AZURE,
        });
    }
    async doInitialize() {
        const apiKey = this.getEffectiveApiKey();
        const baseUrl = this.getEffectiveBaseUrl();
        if (!apiKey) {
            throw new Error('Azure OpenAI API key not found');
        }
        if (!baseUrl) {
            throw new Error('Azure OpenAI endpoint not configured. Set AZURE_OPENAI_ENDPOINT or provide baseUrl in config.');
        }
        // Validate endpoint format
        if (!baseUrl.includes('openai.azure.com')) {
            console.warn('Azure OpenAI endpoint should contain "openai.azure.com"');
        }
    }
    isConfigured() {
        const apiKey = this.getEffectiveApiKey();
        const baseUrl = this.getEffectiveBaseUrl();
        return !!apiKey && !!baseUrl;
    }
    async getAvailableModels() {
        // Azure uses deployment names, but the underlying models are OpenAI models
        return OPENAI_MODELS.map((model) => ({
            ...model,
            provider: ProviderType.AZURE,
        }));
    }
    async doHealthCheck() {
        const apiKey = this.getEffectiveApiKey();
        const baseUrl = this.getEffectiveBaseUrl();
        const apiVersion = this.config.customHeaders?.['api-version'] ||
            AzureProvider.DEFAULT_API_VERSION;
        if (!apiKey || !baseUrl) {
            throw new Error('Azure OpenAI not properly configured');
        }
        // Try to list deployments
        const response = await fetch(`${baseUrl}/openai/deployments?api-version=${apiVersion}`, {
            headers: {
                'api-key': apiKey,
                ...this.config.customHeaders,
            },
        });
        if (!response.ok) {
            throw new Error(`Azure health check failed: ${response.status}`);
        }
    }
    async createCompletion(model, messages, options) {
        const apiKey = this.getEffectiveApiKey();
        const baseUrl = this.getEffectiveBaseUrl();
        const apiVersion = this.config.customHeaders?.['api-version'] ||
            AzureProvider.DEFAULT_API_VERSION;
        if (!apiKey || !baseUrl) {
            throw new Error('Azure OpenAI not configured');
        }
        // Azure uses deployment names instead of model IDs
        const deploymentName = model;
        const url = `${baseUrl}/openai/deployments/${deploymentName}/chat/completions?api-version=${apiVersion}`;
        const response = await fetch(url, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'api-key': apiKey,
                ...this.config.customHeaders,
            },
            body: JSON.stringify({
                messages,
                max_tokens: options?.max_tokens,
                temperature: options?.temperature,
                top_p: options?.top_p,
                stream: false,
                ...options,
            }),
        });
        if (!response.ok) {
            const error = await response.text();
            throw new Error(`Azure OpenAI API error: ${response.status} - ${error}`);
        }
        return await response.json();
    }
    async *createStreamingCompletion(model, messages, options) {
        const apiKey = this.getEffectiveApiKey();
        const baseUrl = this.getEffectiveBaseUrl();
        const apiVersion = this.config.customHeaders?.['api-version'] ||
            AzureProvider.DEFAULT_API_VERSION;
        if (!apiKey || !baseUrl) {
            throw new Error('Azure OpenAI not configured');
        }
        const deploymentName = model;
        const url = `${baseUrl}/openai/deployments/${deploymentName}/chat/completions?api-version=${apiVersion}`;
        const response = await fetch(url, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'api-key': apiKey,
                ...this.config.customHeaders,
            },
            body: JSON.stringify({
                messages,
                max_tokens: options?.max_tokens,
                temperature: options?.temperature,
                top_p: options?.top_p,
                stream: true,
                ...options,
            }),
        });
        if (!response.ok) {
            const error = await response.text();
            throw new Error(`Azure OpenAI API error: ${response.status} - ${error}`);
        }
        if (!response.body) {
            throw new Error('No response body');
        }
        const reader = response.body.getReader();
        const decoder = new TextDecoder();
        let buffer = '';
        try {
            while (true) {
                const { done, value } = await reader.read();
                if (done)
                    break;
                buffer += decoder.decode(value, { stream: true });
                const lines = buffer.split('\n');
                buffer = lines.pop() || '';
                for (const line of lines) {
                    if (line.trim() === '' || !line.startsWith('data: '))
                        continue;
                    const data = line.slice(6);
                    if (data === '[DONE]')
                        continue;
                    try {
                        const parsed = JSON.parse(data);
                        yield parsed;
                    }
                    catch (e) {
                        // Skip invalid JSON
                    }
                }
            }
        }
        finally {
            reader.releaseLock();
        }
    }
    /**
     * Get Azure-specific configuration
     */
    getAzureConfig() {
        return {
            endpoint: this.getEffectiveBaseUrl(),
            apiVersion: this.config.customHeaders?.['api-version'] ||
                AzureProvider.DEFAULT_API_VERSION,
            region: this.config.region,
        };
    }
}
//# sourceMappingURL=azureProvider.js.map