import { Injectable, Logger } from '@nestjs/common';
import { ConfigService } from '@nestjs/config';
import type { AiProvider, AiGenerateInput, AiGenerateOutput } from './ai-provider.interface';

@Injectable()
export class MiniMaxProvider implements AiProvider {
  readonly name = 'minimax';
  private readonly logger = new Logger(MiniMaxProvider.name);
  private readonly apiKey: string;
  private readonly baseUrl: string;

  constructor(private readonly config: ConfigService) {
    this.apiKey = this.config.get<string>('ai.minimax.apiKey', '');
    this.baseUrl = this.config.get<string>('ai.minimax.baseUrl', 'https://api.minimaxi.com');
  }

  async generate(input: AiGenerateInput): Promise<AiGenerateOutput> {
    const start = Date.now();

    if (!this.apiKey) {
      throw new Error('MiniMax API key not configured');
    }

    const body: Record<string, any> = {
      model: input.model,
      messages: input.messages,
      temperature: input.temperature ?? 0.3,
      max_tokens: input.maxTokens ?? 4096,
    };

    if (input.responseFormat?.type === 'json_object') {
      body.response_format = { type: 'json_object' };
    }

    const response = await fetch(`${this.baseUrl}/v1/chat/completions`, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        Authorization: `Bearer ${this.apiKey}`,
      },
      body: JSON.stringify(body),
      signal: input.signal,
    });

    if (!response.ok) {
      const errorText = await response.text().catch(() => 'unknown');
      this.logger.error(`MiniMax API error ${response.status}: ${errorText}`);
      throw new Error(`MiniMax API returned ${response.status}`);
    }

    const data = await response.json();
    const latencyMs = Date.now() - start;

    const content = data.choices?.[0]?.message?.content ?? '';
    const usage = data.usage ?? {};

    return {
      rawText: content,
      usage: {
        model: input.model,
        inputTokens: usage.prompt_tokens ?? 0,
        outputTokens: usage.completion_tokens ?? 0,
      },
      latencyMs,
    };
  }
}
