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 TongyiAdapter 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/text/generation', {
          model,
          input: {
            prompt,
            max_tokens: config?.max_tokens || 1000,
            temperature: config?.temperature || 0.7,
            top_p: config?.top_p || 1,
            stop: config?.stop || [],
          }
        })
      );

      if (response.data && response.data.output && response.data.output.text) {
        return response.data.output.text;
      }
      
      throw new Error('Invalid response from Tongyi API');
    } catch (error:any) {
      console.error('Tongyi 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: messages.map(msg => ({
            role: msg.role,
            content: msg.content
          })),
          parameters: {
            max_tokens: config?.max_tokens || 1000,
            temperature: config?.temperature || 0.7,
            top_p: config?.top_p || 1,
            stop: config?.stop || [],
          }
        })
      );

      if (response.data && response.data.output && response.data.output.text) {
        return response.data.output.text;
      }
      
      throw new Error('Invalid response from Tongyi API');
    } catch (error:any) {
      console.error('Tongyi API error:', error.response?.data || error.message);
      throw new Error(`Failed to chat: ${error.message}`);
    }
  }
}