import { HttpService } from '@nestjs/axios';
import { Injectable } from '@nestjs/common';
import { firstValueFrom } from 'rxjs';
import { AiConfig } from './ai-config.entity';
import { AiServiceAdapter } from './ai.adapter';

@Injectable()
export class DeepSeekAdapter implements AiServiceAdapter {
  private readonly httpService: HttpService;

  constructor(private readonly config: AiConfig) {
    this.httpService = new HttpService({
      baseURL: this.config.apiUrl,
      headers: {
        'Authorization': `Bearer ${this.config.apiKey}`,
        'Content-Type': 'application/json',
      },
    });
  }

  /**
   * 生成文本
   * @param model 模型名称
   * @param prompt 提示文本
   * @param config 可选配置
   * @returns 生成的文本
   */
  async generateText(model: string, prompt: string, config?: Record<string, any>): Promise<string> {
    try {
      const response = await firstValueFrom(
        this.httpService.post('/v1/completions', {
          model,
          prompt,
          max_tokens: config?.max_tokens || 1000,
          temperature: config?.temperature || 0.7,
          top_p: config?.top_p || 1,
          frequency_penalty: config?.frequency_penalty || 0,
          presence_penalty: config?.presence_penalty || 0,
        })
      );

      if (response.data && response.data.choices && response.data.choices.length > 0) {
        return response.data.choices[0].text;
      }
      
      throw new Error('Invalid response from DeepSeek API');
    } catch (error:any) {
      console.error('DeepSeek API error:', error.response?.data || error.message);
      throw new Error(`Failed to generate text: ${error.message}`);
    }
  }

  /**
   * 聊天对话
   * @param model 模型名称
   * @param messages 消息数组
   * @param config 可选配置
   * @returns 聊天回复
   */
  async chat(model: string, messages: Array<{role: string, content: string}>, config?: Record<string, any>): Promise<string> {
    try {
      const response = await firstValueFrom(
        this.httpService.post('/v1/chat/completions', {
          model,
          messages,
          max_tokens: config?.max_tokens || 1000,
          temperature: config?.temperature || 0.7,
          top_p: config?.top_p || 1,
          frequency_penalty: config?.frequency_penalty || 0,
          presence_penalty: config?.presence_penalty || 0,
        })
      );

      if (response.data && response.data.choices && response.data.choices.length > 0) {
        return response.data.choices[0].message.content;
      }
      
      throw new Error('Invalid response from DeepSeek API');
    } catch (error:any) {
      console.error('DeepSeek API error:', error.response?.data || error.message);
      throw new Error(`Failed to chat: ${error.message}`);
    }
  }
}