import { HttpMethod } from '../../../../plugins/shared/types';
import ChatGptRequest from './ChatGptRequest';
import { FastifyReply } from 'fastify';
import { ChatGptResponse, OpenAIResponse, ChatGptRequestBody } from '../../types/chatgpt';

export class ChatGptService {
    private endpoint: string = '/chat/completions';

    async sendMessageToChatGpt(requestBody: Record<string, unknown>, reply: FastifyReply): Promise<ChatGptResponse> {
        try {
            let messages: { role: string; content: string }[];
            let responseFormat: string | undefined;

            if ('data' in requestBody && typeof requestBody.data === 'string') {
                messages = [
                    {
                        role: 'system',
                        content: `You are an assistant for a developer tool. When the user asks for a Canvas API endpoint, respond ONLY with a JSON object in this format:\n{\n  "name": "Get All Courses",\n  "method": "GET",\n  "path": "/courses",\n  "description": "Retrieves all courses from Canvas"\n}\nDo not include any explanation, just the JSON. Use the official Canvas API documentation to determine the correct method and path. The path should be exactly as in the Canvas API documentation, e.g., '/courses', and should NOT include any base URL or prefix such as '/api/v1'.`
                    },
                    { role: 'user', content: requestBody.data as string }
                ];
                responseFormat = requestBody.responseFormat as string;
            } else if (
                'messages' in requestBody &&
                Array.isArray(requestBody.messages) &&
                requestBody.messages.length > 0
            ) {
                messages = requestBody.messages as { role: string; content: string }[];
                responseFormat = requestBody.responseFormat as string;
            } else {
                throw new Error("Missing required parameter: 'messages' or 'data'");
            }

            if (!('model' in requestBody) || typeof requestBody.model !== 'string') {
                requestBody.model = 'gpt-4';
            }

            const formattedRequest: ChatGptRequestBody = {
                model: requestBody.model as string,
                messages,
                response_format: responseFormat === 'json' ? { type: 'json_object' } : undefined
            };

            const response = await ChatGptRequest.doRequest<OpenAIResponse>("POST", this.endpoint, formattedRequest);

            const responseText = response?.choices?.[0]?.message?.content ?? 'No response from ChatGPT';

            let parsedResponse: string | object = responseText;
            if (responseFormat === 'json') {
                try {
                    parsedResponse = JSON.parse(responseText);
                } catch (e) {
                    console.error('Failed to parse JSON response:', e);
                    throw new Error('Invalid JSON response from ChatGPT');
                }
            }

            return { responseText: parsedResponse };
        } catch (error) {
            console.error('Error handling ChatGPT request:', error);
            const errorMessage = error instanceof Error ? error.message : 'Failed to process request';
            if (!reply.sent) {
                reply.status(500).send({ responseText: '', errorMessage });
            }
            return { responseText: '', errorMessage };
        }
    }
} 