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

@Injectable()
export class SiliconFlowProvider implements AiProvider {
  readonly name = 'siliconflow';

  private getConfig() {
    return {
      baseUrl: process.env.SILICONFLOW_BASE_URL || 'https://api.siliconflow.cn/v1',
      apiKey: process.env.SILICONFLOW_API_KEY || '',
    };
  }

  async generate(input: AiGenerateInput): Promise<AiGenerateOutput> {
    const { baseUrl, apiKey } = this.getConfig();
    const start = Date.now();

    const resp = await fetch(`${baseUrl}/chat/completions`, {
      method: 'POST',
      headers: { 'Content-Type': 'application/json', Authorization: `Bearer ${apiKey}` },
      body: JSON.stringify({
        model: input.model,
        messages: input.messages,
        temperature: input.temperature ?? 0.3,
        max_tokens: input.maxTokens ?? 4096,
      }),
      signal: input.signal ?? AbortSignal.timeout(60_000),
    });

    if (!resp.ok) throw new Error(`SiliconFlow ${resp.status}: ${(await resp.text()).slice(0, 200)}`);
    const data = await resp.json();
    const choice = data.choices?.[0];
    return {
      rawText: choice?.message?.content || '',
      usage: { model: input.model, inputTokens: data.usage?.prompt_tokens || 0, outputTokens: data.usage?.completion_tokens || 0 },
      latencyMs: Date.now() - start,
    };
  }
}
