#include "instructionmanager.h"
#include "uosai_global.h"
#include "instructions.h"
#include "../chat/private/eaicallbck.h"

#include <QJsonArray>

UOSAI_USE_NAMESPACE

InstructionManager *InstructionManager::instance()
{
    static InstructionManager ins;
    return &ins;
}

InstructionManager::InstructionManager()
{
    init();
}

void InstructionManager::init()
{
    QSharedPointer<InstructionWorker> sysCtrInst;
    sysCtrInst.reset(new SystemControlInst());
    QSharedPointer<InstructionWorker> launchAppInst;
    launchAppInst.reset(new LaunchAppInst());
    QSharedPointer<InstructionWorker> sendMailInst;
    sendMailInst.reset(new SendMailInst());
    QSharedPointer<InstructionWorker> createScheduleInst;
    createScheduleInst.reset(new CreateScheduleInst());
    QSharedPointer<InstructionWorker> genImageInst;
    genImageInst.reset(new GenerateImageInst());
    QSharedPointer<InstructionWorker> searchInst;
    searchInst.reset(new SearchOnlineInst());

    instWorkers = {
        {SystemControl, sysCtrInst},
        {LaunchApp, launchAppInst},
        {SendMail, sendMailInst},
        {CreateSchedule, createScheduleInst},
        {GenerateImage, genImageInst},
        {SearchOnline, searchInst},
    };
}

QString InstructionManager::query(AssistantType type, LLMChatModel model)
{
    QJsonArray resultArray;
    for (int inst: instWorkers.keys()) {
        QSharedPointer<InstructionWorker> instWorker = instWorkers.value(inst);
        if (!instWorker->isAvailable(type, model))
            continue;

        QJsonObject instObj;
        instObj.insert("tagType", inst);
        instObj.insert("tagName", instWorker->getTagName());
        instObj.insert("content", instWorker->getContent());
        instObj.insert("description", instWorker->getDescription());

        resultArray.append(instObj);
    }

    return QJsonDocument(resultArray).toJson(QJsonDocument::Compact);
}

QSharedPointer<EAiPrompt> InstructionManager::genPrompt(int inst, const QString &userData)
{
    QSharedPointer<InstructionWorker> instWorker = instWorkers.value(inst);

    QSharedPointer<EAiPrompt> aiPrompt;
    aiPrompt = instWorker->genPrompt(userData);

    return aiPrompt;
}

QString InstructionManager::onAiCallback(int inst, QString aiReply)
{
    QSharedPointer<InstructionWorker> instWorker = instWorkers.value(inst);

    return instWorker->run(aiReply);
}
