import superagent from 'superagent'
import fs from 'fs'

const aiBaseUrl = 'https://api.tech.ec.europa.eu/ecgpt/v1/'
const aiUrlModel = aiBaseUrl + 'models'
const aiUrlCompletion = aiBaseUrl + 'chat/completions' // 
const aiUrlQuota = aiBaseUrl + 'quota-consumption/' // 'quota-consumption/${model_id}'
const gptResponseFile = 'gptjsonresponse.json';
const gptResponseCleanFile = 'gptcleanresponse.json'

//const models = ["mistral-small-24b-instruct-2501","llama-3.3-70b-instruct","llama-3.1-8b-instruct","gpt-4o"]

export default class AiService {

    constructor(config) {
        this.request = superagent;
        this.config = config;
        this.apiKey = process.env.apiKey//set on ~/.bashrc
        this.gptResponseFile = gptResponseFile
        this.gptResponseCleanFile = gptResponseCleanFile
    }
    async getModels() {
        let data = {}
        let models = await this.runGet(aiUrlModel, data);
        let jsonResponse = JSON.stringify(models.text)
        console.log('Gpt@ec models: ', jsonResponse);
        return jsonResponse;
    }
    async getQuota(modelId) {
        let data = { 'model_id': modelId }
        let result = JSON.stringify((await this.runGet(aiUrlQuota + modelId, data)).text)
        console.log('Gpt@ec quota for: '+ modelId, result)
        return result;
    }
    async processInfo(content, model = "mistral-small-24b-instruct-2501", maxTokens = 30000, writeResultFile = true) {
        let data = {
            "model": model,
            "loc" : "body",
            "messages": [
            //{"content": '',"role": "system"},
            {
                "content": content,
                "role": "user"
            }],
            "max_tokens": maxTokens
        }
        let result = await this.runPost(aiUrlCompletion, data);
        let resultText = await result._body.choices[0].message.content
        if (writeResultFile) {
            await fs.writeFileSync(gptResponseFile, JSON.stringify(resultText));
        }
        return resultText;
    }
    async runPost(url, data) {
        let response = false;
        if (this.apiKey) {
            if (data) {
                response = await this.request
                    .post(url)
                    .type('json')
                    .set('Authorization', `Bearer ${this.apiKey}`)
                    .send(data);
            } else {
                response = await this.request
                    .post(url)
                    .set('Authorization', `Bearer ${this.apiKey}`)
                    .send();
            }
        } else {
            response = await this.request
                .post(url)
                .type('json')
                .send(data);
        }
        return response;
    }
    async runGet(url, data) {
        let response = false;
        if (this.apiKey) {
            if (data) {
                response = await this.request
                    .get(url)
                    .type('json')
                    .set('Authorization', `Bearer ${this.apiKey}`)
                    .send(data);
            } else {
                response = await this.request
                    .post(url)
                    .set('Authorization', `Bearer ${this.apiKey}`)
                    .send();
            }
        } else {
            response = await this.request
                .get(url)
                .type('json')
                .send(data);
        }
        return response;
    }
    async parseGptJsonResponse(text, showObj = false) {
        try {
            if(!text){
                text = await fs.readFileSync(gptResponseFile).toString('utf-8');
            }
            text = text.replace(/^.*?\{/g, '').trim()
            text = text.replace(/```json|```/g, '').trim()
            text = text.replace(/\\n/g, '').trim()
            text = text.replaceAll(/\n\n/g, '')
            text = text.replaceAll(/\\"/g, '"')
            text = text.replaceAll(/\"\[/g, '[')
            text = text.replaceAll(/\]"/g, ']')
            text = text.replaceAll(/\"{/g, '{')
            text = text.replaceAll(/\}"/g, '}')
            let cleanObj = JSON.parse(text);
            if(showObj){
                console.log('Clean object : ', cleanObj);
            }
            await fs.writeFileSync( gptResponseCleanFile, JSON.stringify(cleanObj));
            return cleanObj;
        } catch (e) {
            throw new Error('Failed to parse GPT JSON response: ' + e.message);
        }
    }
}
