import type { EmbeddingProvider } from '../types.js';

/**
 * Fireworks embedding provider
 *
 * Uses Fireworks AI's nomic-embed-text model
 */
export class FireworksEmbeddingProvider implements EmbeddingProvider {
  name = 'fireworks';
  model: string;
  dimensions: number;
  private apiKey: string;
  private baseUrl: string;

  constructor(options: {
    model?: string;
    dimensions?: number;
    apiKey?: string;
  } = {}) {
    this.model = options.model ?? 'nomic-ai/nomic-embed-text-v1.5';
    this.dimensions = options.dimensions ?? 768;
    this.apiKey = options.apiKey ?? process.env.FIREWORKS_API_KEY ?? '';
    this.baseUrl = 'https://api.fireworks.ai/inference/v1';

    if (!this.apiKey) {
      throw new Error('Fireworks API key is required. Set FIREWORKS_API_KEY environment variable.');
    }
  }

  async embed(texts: string[]): Promise<number[][]> {
    const response = await fetch(`${this.baseUrl}/embeddings`, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        'Authorization': `Bearer ${this.apiKey}`,
      },
      body: JSON.stringify({
        model: this.model,
        input: texts,
      }),
    });

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

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

    // Sort by index to preserve order
    return data.data
      .sort((a, b) => a.index - b.index)
      .map((item) => item.embedding);
  }

  async embedSingle(text: string): Promise<number[]> {
    const results = await this.embed([text]);
    return results[0];
  }
}
