"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.generateStepSlug = exports.generateCodeChallenge = exports.addInteractivity = exports.initialContentGenerator = exports.getLanguageCodes = exports.isPackageAuthor = exports.fillSidebarJSON = exports.generateCourseShortName = exports.isValidRigoToken = exports.translateCourseMetadata = exports.createStructuredPreviewReadme = exports.readmeCreator = exports.createCodingReadme = exports.createCodeFile = exports.interactiveCreation = exports.generateCourseIntroduction = exports.translateExercise = exports.generateImage = exports.hasCreatorPermission = exports.createReadme = void 0;
exports.downloadImage = downloadImage;
exports.createPreviewReadme = createPreviewReadme;
exports.makeReadmeReadable = makeReadmeReadable;
const axios_1 = require("axios");
const promises_1 = require("fs/promises");
const console_1 = require("../utils/console");
const fs = require("fs");
const path = require("path");
const api_1 = require("./api");
const createReadme = async (token, inputs, purpose, webhookUrl) => {
    try {
        const response = await axios_1.default.post(`${api_1.RIGOBOT_HOST}/v1/prompting/completion/create-sequencial-readme/`, {
            inputs,
            include_purpose_objective: true,
            execute_async: !!webhookUrl,
            purpose_slug: purpose,
            webhook_url: webhookUrl,
        }, {
            headers: {
                "Content-Type": "application/json",
                Authorization: "Token " + token.trim(),
            },
        });
        return response.data;
    }
    catch (error) {
        console.error(error);
        return null;
    }
};
exports.createReadme = createReadme;
const hasCreatorPermission = async (token) => {
    console_1.default.debug("Checking if user has creator permission");
    try {
        const response = await axios_1.default.get(`${api_1.RIGOBOT_HOST}/v1/learnpack/permissions/creator`, {
            headers: {
                "Content-Type": "application/json",
                Authorization: "Token " + token,
            },
        });
        // If the status code is 403, it means no permission
        if (response.status === 403)
            return false;
        console_1.default.debug("The user is a creator! 🎉");
        return true;
    }
    catch (error) {
        console_1.default.error(error);
        return false;
    }
};
exports.hasCreatorPermission = hasCreatorPermission;
const generateImage = async (token, { prompt, callbackUrl }) => {
    try {
        const response = await axios_1.default.post(`${api_1.RIGOBOT_HOST}/v1/learnpack/tools/images`, {
            prompt,
            webhook_callback_url: callbackUrl,
            provider: "bfl",
            model: "flux-pro-1.1",
        }, {
            headers: {
                "Content-Type": "application/json",
                Authorization: "Token " + token,
            },
        });
        return response.data;
    }
    catch (error) {
        console_1.default.debug(error);
        return null;
    }
};
exports.generateImage = generateImage;
async function downloadImage(imageUrl, savePath) {
    const response = await axios_1.default.get(imageUrl, { responseType: "arraybuffer" });
    const buffer = Buffer.from(response.data, "binary");
    await (0, promises_1.writeFile)(savePath, buffer);
}
const translateExercise = async (token, inputs, webhookUrl) => {
    const response = await axios_1.default.post(`${api_1.RIGOBOT_HOST}/v1/prompting/completion/translate-asset-markdown/`, {
        inputs: inputs,
        include_purpose_objective: false,
        execute_async: true,
        webhook_url: webhookUrl,
    }, {
        headers: {
            "Content-Type": "application/json",
            Authorization: "Token " + token,
        },
    });
    return response.data;
};
exports.translateExercise = translateExercise;
const generateCourseIntroduction = async (token, inputs) => {
    const response = await axios_1.default.post(`${api_1.RIGOBOT_HOST}/v1/prompting/completion/192/`, {
        inputs: inputs,
        include_purpose_objective: false,
        execute_async: false,
    }, {
        headers: {
            "Content-Type": "application/json",
            Authorization: "Token " + token,
        },
    });
    return response.data;
};
exports.generateCourseIntroduction = generateCourseIntroduction;
const interactiveCreation = async (token, inputs) => {
    const response = await axios_1.default.post(`${api_1.RIGOBOT_HOST}/v1/prompting/completion/390/`, {
        inputs: inputs,
        include_purpose_objective: false,
        execute_async: false,
    }, {
        headers: {
            "Content-Type": "application/json",
            Authorization: "Token " + token,
        },
    });
    return response.data;
};
exports.interactiveCreation = interactiveCreation;
const createCodeFile = async (token, inputs) => {
    const response = await axios_1.default.post(`${api_1.RIGOBOT_HOST}/v1/prompting/completion/456/`, {
        inputs: inputs,
        include_purpose_objective: false,
        execute_async: false,
    }, {
        headers: {
            "Content-Type": "application/json",
            Authorization: "Token " + token,
        },
    });
    return response.data;
};
exports.createCodeFile = createCodeFile;
const createCodingReadme = async (token, inputs, purpose, webhookUrl) => {
    const response = await axios_1.default.post(`${api_1.RIGOBOT_HOST}/v1/prompting/completion/create-coding-exercise/`, {
        inputs,
        include_purpose_objective: true,
        purpose_slug: purpose,
        execute_async: !!webhookUrl,
        webhook_url: webhookUrl,
    }, {
        headers: {
            "Content-Type": "application/json",
            Authorization: "Token " + token,
        },
    });
    return response.data;
};
exports.createCodingReadme = createCodingReadme;
const readmeCreator = async (token, inputs, purpose, webhookUrl) => {
    if (inputs.kind === "quiz" || inputs.kind === "read") {
        const createReadmeInputs = {
            title: inputs.title,
            output_lang: inputs.output_lang,
            list_of_exercises: inputs.list_of_exercises,
            tutorial_description: inputs.tutorial_description,
            include_quiz: inputs.kind === "quiz" ? "true" : "false",
            lesson_description: inputs.lesson_description,
            prev_lesson: inputs.last_lesson,
        };
        return (0, exports.createReadme)(token, createReadmeInputs, purpose, webhookUrl);
    }
    if (inputs.kind === "code") {
        return (0, exports.createCodingReadme)(token, {
            title: inputs.title,
            output_lang: inputs.output_lang,
            list_of_exercises: inputs.list_of_exercises,
            tutorial_info: inputs.tutorial_description,
            lesson_description: inputs.lesson_description,
            prev_lesson: inputs.last_lesson,
        }, purpose, webhookUrl);
    }
    throw new Error("Invalid kind of lesson");
};
exports.readmeCreator = readmeCreator;
const createStructuredPreviewReadme = async (token, inputs, webhookUrl) => {
    const response = await axios_1.default.post(`${api_1.RIGOBOT_HOST}/v1/prompting/completion/write-course-introduction-readme/`, {
        inputs: inputs,
        include_purpose_objective: false,
        webhook_url: webhookUrl,
    }, {
        headers: {
            "Content-Type": "application/json",
            Authorization: "Token " + token.trim(),
        },
    });
    return response.data;
};
exports.createStructuredPreviewReadme = createStructuredPreviewReadme;
const translateCourseMetadata = async (token, inputs) => {
    const response = await axios_1.default.post(`${api_1.RIGOBOT_HOST}/v1/prompting/completion/translate-course-metadata/`, { inputs, include_purpose_objective: false, execute_async: false }, {
        headers: {
            "Content-Type": "application/json",
            Authorization: "Token " + token,
        },
    });
    return response.data;
};
exports.translateCourseMetadata = translateCourseMetadata;
async function createPreviewReadme(tutorialDir, packageInfo, rigoToken, readmeContents) {
    const readmeFilename = `README.md`;
    const readmeContent = await (0, exports.generateCourseIntroduction)(rigoToken, {
        course_title: packageInfo.title.us,
        lessons_context: readmeContents.join("\n"),
    });
    fs.writeFileSync(path.join(tutorialDir, readmeFilename), readmeContent.answer);
}
async function makeReadmeReadable(rigoToken, inputs, purpose) {
    try {
        const response = await axios_1.default.post(`${api_1.RIGOBOT_HOST}/v1/prompting/completion/588/`, { inputs, include_purpose_objective: false, execute_async: false }, {
            headers: {
                "Content-Type": "application/json",
                Authorization: "Token " + rigoToken,
            },
        });
        return response.data;
    }
    catch (error) {
        console_1.default.debug(error);
        return null;
    }
}
const isValidRigoToken = async (rigobotToken) => {
    const rigoUrl = `${api_1.RIGOBOT_HOST}/v1/auth/token/${rigobotToken}`;
    const rigoResp = await fetch(rigoUrl);
    if (!rigoResp.ok) {
        console_1.default.debug("Invalid Rigobot token", rigoResp.status);
        console_1.default.debug(rigoResp.statusText);
        return false;
    }
    return true;
};
exports.isValidRigoToken = isValidRigoToken;
const generateCourseShortName = async (token, inputs) => {
    const response = await axios_1.default.post(`${api_1.RIGOBOT_HOST}/v1/prompting/completion/852/`, { inputs, include_purpose_objective: false, execute_async: false }, {
        headers: {
            "Content-Type": "application/json",
            Authorization: "Token " + token,
        },
    });
    return response.data;
};
exports.generateCourseShortName = generateCourseShortName;
const fillSidebarJSON = async (token, inputs) => {
    const response = await axios_1.default.post(`${api_1.RIGOBOT_HOST}/v1/prompting/completion/951/`, { inputs, include_purpose_objective: false, execute_async: false }, {
        headers: {
            "Content-Type": "application/json",
            Authorization: "Token " + token,
        },
    });
    return response.data;
};
exports.fillSidebarJSON = fillSidebarJSON;
const isPackageAuthor = async (token, packageSlug) => {
    var _a;
    const url = `${api_1.RIGOBOT_HOST}/v1/learnpack/package/${packageSlug}/`;
    const headers = {
        Authorization: `Token ${token}`,
    };
    try {
        const response = await axios_1.default.get(url, { headers });
        return { isAuthor: response.status === 200, status: response.status };
    }
    catch (error) {
        const status = ((_a = error === null || error === void 0 ? void 0 : error.response) === null || _a === void 0 ? void 0 : _a.status) || 500;
        console.error("Error fetching package:", error);
        return { isAuthor: false, status };
    }
};
exports.isPackageAuthor = isPackageAuthor;
const getLanguageCodes = async (token, inputs) => {
    const response = await axios_1.default.post(`${api_1.RIGOBOT_HOST}/v1/prompting/completion/get-language-codes/`, { inputs, include_purpose_objective: false, execute_async: false }, {
        headers: {
            "Content-Type": "application/json",
            Authorization: "Token " + token,
        },
    });
    return response.data;
};
exports.getLanguageCodes = getLanguageCodes;
const initialContentGenerator = async (token, inputs, webhookUrl, endpointSlug = "initial-step-content-generator") => {
    try {
        const response = await axios_1.default.post(`${api_1.RIGOBOT_HOST}/v1/prompting/completion/${endpointSlug}/`, {
            inputs,
            include_purpose_objective: false,
            execute_async: !!webhookUrl,
            webhook_url: webhookUrl,
        }, {
            headers: {
                "Content-Type": "application/json",
                Authorization: "Token " + token.trim(),
            },
        });
        return response.data;
    }
    catch (error) {
        console.error("Error in initialContentGenerator:", error);
        return null;
    }
};
exports.initialContentGenerator = initialContentGenerator;
const addInteractivity = async (token, inputs, webhookUrl) => {
    try {
        const response = await axios_1.default.post(`${api_1.RIGOBOT_HOST}/v1/prompting/completion/add-lesson-interactivy/`, {
            inputs,
            include_purpose_objective: false,
            execute_async: !!webhookUrl,
            webhook_url: webhookUrl,
        }, {
            headers: {
                "Content-Type": "application/json",
                Authorization: "Token " + token.trim(),
            },
        });
        return response.data;
    }
    catch (error) {
        console.error("Error in addInteractivity:", error);
        return null;
    }
};
exports.addInteractivity = addInteractivity;
const generateCodeChallenge = async (token, inputs, webhookUrl) => {
    try {
        const response = await axios_1.default.post(`${api_1.RIGOBOT_HOST}/v1/prompting/completion/create-structured-coding-filles/`, {
            inputs,
            include_purpose_objective: false,
            execute_async: !!webhookUrl,
            webhook_url: webhookUrl,
        }, {
            headers: {
                "Content-Type": "application/json",
                Authorization: "Token " + token.trim(),
            },
        });
        return response.data;
    }
    catch (error) {
        console.error("Error in generateCodeChallenge:", error);
        return null;
    }
};
exports.generateCodeChallenge = generateCodeChallenge;
const generateStepSlug = async (token, inputs) => {
    try {
        const response = await axios_1.default.post(`${api_1.RIGOBOT_HOST}/v1/prompting/completion/step-slug-generator/`, { inputs, include_purpose_objective: false, execute_async: false }, {
            headers: {
                "Content-Type": "application/json",
                Authorization: "Token " + token.trim(),
            },
        });
        return response.data;
    }
    catch (error) {
        console.error("Error in createStep:", error);
        return null;
    }
};
exports.generateStepSlug = generateStepSlug;
