/**
 * Azure OpenAI LLM provider.
 *
 * Uses Azure OpenAI REST API with api-key authentication.
 * Reads config from AZURE_OPENAI_ENDPOINT, AZURE_OPENAI_KEY, AZURE_OPENAI_DEPLOYMENT.
 */

import type { ChatCompletionRequest, ChatCompletionResponse, LLMProvider } from '../types.js';

export interface AzureOpenAIConfig {
  endpoint: string;
  apiKey: string;
  deployment: string;
  apiVersion?: string;
}

export class AzureOpenAIProvider implements LLMProvider {
  private config: AzureOpenAIConfig;

  constructor(config?: Partial<AzureOpenAIConfig>) {
    this.config = {
      endpoint: config?.endpoint || process.env.AZURE_OPENAI_ENDPOINT || '',
      apiKey: config?.apiKey || process.env.AZURE_OPENAI_KEY || process.env.OPENAI_API_KEY || '',
      deployment:
        config?.deployment ||
        process.env.AZURE_OPENAI_DEPLOYMENT ||
        process.env.OPENAI_MODEL ||
        'gpt-4o-mini',
      apiVersion: config?.apiVersion || process.env.AZURE_OPENAI_API_VERSION || '2024-06-01',
    };
  }

  isConfigured(): boolean {
    return Boolean(this.config.endpoint && this.config.apiKey && this.config.deployment);
  }

  async chatCompletion(req: ChatCompletionRequest): Promise<ChatCompletionResponse> {
    if (!this.isConfigured()) {
      throw new Error(
        'Azure OpenAI is not configured (missing AZURE_OPENAI_ENDPOINT or AZURE_OPENAI_KEY)'
      );
    }

    const base = this.config.endpoint.replace(/\/+$/, '');
    const url = `${base}/openai/deployments/${encodeURIComponent(this.config.deployment)}/chat/completions?api-version=${encodeURIComponent(this.config.apiVersion!)}`;

    const body = {
      messages: req.messages,
      temperature: req.temperature,
      max_tokens: req.maxTokens,
      top_p: req.topP,
      stop: req.stop,
      response_format: req.responseFormat,
    };

    const response = await fetch(url, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        'api-key': this.config.apiKey,
      },
      body: JSON.stringify(body),
    });

    if (!response.ok) {
      const text = await response.text();
      throw new Error(`Azure OpenAI error ${response.status}: ${text}`);
    }

    const data = (await response.json()) as {
      choices: Array<{ message: { content: string }; finish_reason: string }>;
      model: string;
      usage: { prompt_tokens: number; completion_tokens: number; total_tokens: number };
    };

    return {
      content: data.choices[0]?.message?.content ?? '',
      model: data.model,
      finishReason:
        (data.choices[0]?.finish_reason as ChatCompletionResponse['finishReason']) ?? null,
      usage: {
        promptTokens: data.usage.prompt_tokens,
        completionTokens: data.usage.completion_tokens,
        totalTokens: data.usage.total_tokens,
      },
    };
  }
}
