import { Injectable, Logger } from '@nestjs/common';
import envConfig from 'src/common/config/envConfig';
import { HttpService } from '@nestjs/axios';
import { CHAT_FUNCTION_CALL_TYPES } from '../chat-history.constant';
import { OPEN_AI_DEFAULT_MODEL } from 'src/shared/third-party/services/chat-gpt/chat-gpt.constant';

// {"role": "system", "content": "You are a helpful assistant designed to output JSON."},

export interface IChatGptMessage {
    role: 'assistant' | 'user' | 'system';
    content: string;
    fullContent?: string;
}


@Injectable()
export class ChatGptService {
  private readonly logger = new Logger(ChatGptService.name)

  constructor(private readonly http: HttpService) {}

  async getChatGptResponse(messages: IChatGptMessage[]) {
    let url = 'https://api.openai.com/v1/chat/completions';
    let headers = {
      'Content-Type': 'application/json',
      Authorization: `Bearer ${envConfig().CHAT_GPT_TOKEN}`,
      'Accept-Encoding': 'gzip,deflate,compress',
    };
    let data = {
      model: OPEN_AI_DEFAULT_MODEL,
      messages: messages,
      functions: [
        {
          name: CHAT_FUNCTION_CALL_TYPES.GET_UPTO_DATE_DATA,
          description: 'Get up to date information from the web',
          parameters: {
            type: 'object',
            properties: {
              quary: {
                type: 'string',
                description:
                  'Specify your query to fetch the latest information from the web.',
              },
            },
            required: ['quary'],
          },
        },
        {
          name: CHAT_FUNCTION_CALL_TYPES.GENERATE_IMAGE,
          description: 'Create an image from a description',
          parameters: {
            type: 'object',
            properties: {
              description: {
                type: 'string',
                description:
                  'Provide a detailed description for the image you want to create. the description must alawis be in english ',
              },
            },
            required: ['description'],
          },
        },
        // {
        //   name: CHAT_FUNCTION_CALL_TYPES.GET_DATA_FROM_URL,
        //   description: 'Get data from a url',
        //   parameters: {
        //     type: 'object',
        //     properties: {
        //       url: {
        //         type: 'string',
        //         description:
        //           'Provide a url to fetch the data from the web.',
        //       },
        //     },
        //     required: ['url'],
        //   },
        // }
      ],
      function_call: 'auto',
      temperature: 0.6,
    };
    try {
      let response = await this.http
        .post(url, data, { headers: headers })
        .toPromise();
      return response;
    } catch (error) {
      // console.log(error.response.data);
      this.logger.error(error.response.data);
      return {
        data: {
          choices: [
            {
              finish_reason: 'stop',
              message: {
                content: 'Sorry, we are not able to handle this request',
              },
            },
          ],
          usage: {
            total_tokens: 0,
          },
        },
      };
    }
  }
}
