/**
 * OpenAI direct LLM provider.
 *
 * Uses OpenAI REST API with Bearer token authentication.
 * Reads config from OPENAI_API_KEY, OPENAI_BASE_URL, OPENAI_MODEL.
 * Supports text, vision (multipart content), streaming, and embeddings.
 */

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

export interface OpenAIConfig {
  apiKey: string;
  baseUrl?: string;
  model?: string;
  embeddingModel?: string;
}

export class OpenAIProvider implements LLMProvider {
  private config: OpenAIConfig;

  constructor(config?: Partial<OpenAIConfig>) {
    this.config = {
      apiKey: config?.apiKey || process.env.OPENAI_API_KEY || '',
      baseUrl: config?.baseUrl || process.env.OPENAI_BASE_URL || 'https://api.openai.com/v1',
      model: config?.model || process.env.OPENAI_MODEL || 'gpt-4o-mini',
      embeddingModel:
        config?.embeddingModel || process.env.LLM_EMBEDDING_MODEL || 'text-embedding-3-small',
    };
  }

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

  private getBaseUrl(): string {
    return this.config.baseUrl!.replace(/\/+$/, '');
  }

  private getHeaders(): Record<string, string> {
    return {
      'Content-Type': 'application/json',
      Authorization: `Bearer ${this.config.apiKey}`,
    };
  }

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

    const url = `${this.getBaseUrl()}/chat/completions`;

    const body = {
      model: req.model || this.config.model,
      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: this.getHeaders(),
      body: JSON.stringify(body),
    });

    if (!response.ok) {
      const text = await response.text();
      throw new Error(`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,
      },
    };
  }

  async *chatCompletionStream(req: ChatCompletionRequest): AsyncIterable<string> {
    if (!this.isConfigured()) {
      throw new Error('OpenAI is not configured (missing OPENAI_API_KEY)');
    }

    const url = `${this.getBaseUrl()}/chat/completions`;

    const body = {
      model: req.model || this.config.model,
      messages: req.messages,
      temperature: req.temperature,
      max_tokens: req.maxTokens,
      top_p: req.topP,
      stop: req.stop,
      response_format: req.responseFormat,
      stream: true,
    };

    const response = await fetch(url, {
      method: 'POST',
      headers: this.getHeaders(),
      body: JSON.stringify(body),
    });

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

    if (!response.body) {
      throw new Error('OpenAI streaming: 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) {
          const trimmed = line.trim();
          if (!trimmed || !trimmed.startsWith('data: ')) continue;
          const data = trimmed.slice(6);
          if (data === '[DONE]') return;
          try {
            const parsed = JSON.parse(data) as {
              choices: Array<{ delta: { content?: string } }>;
            };
            const delta = parsed.choices?.[0]?.delta?.content;
            if (delta) yield delta;
          } catch {
            // skip malformed SSE chunks
          }
        }
      }
    } finally {
      reader.releaseLock();
    }
  }

  async embed(req: EmbeddingRequest): Promise<EmbeddingResponse> {
    if (!this.isConfigured()) {
      throw new Error('OpenAI is not configured (missing OPENAI_API_KEY)');
    }

    const url = `${this.getBaseUrl()}/embeddings`;

    const body = {
      model: req.model || this.config.embeddingModel,
      input: req.input,
    };

    const response = await fetch(url, {
      method: 'POST',
      headers: this.getHeaders(),
      body: JSON.stringify(body),
    });

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

    const data = (await response.json()) as {
      data: Array<{ embedding: number[]; index: number }>;
      model: string;
      usage: { prompt_tokens: number; total_tokens: number };
    };

    return {
      embeddings: data.data.sort((a, b) => a.index - b.index).map(d => d.embedding),
      model: data.model,
      usage: {
        promptTokens: data.usage.prompt_tokens,
        completionTokens: 0,
        totalTokens: data.usage.total_tokens,
      },
    };
  }
}
