/*
  SPDX-FileCopyrightText: 2025-2026 Laurent Montel <montel@kde.org>

  SPDX-License-Identifier: GPL-2.0-or-later
*/
#include "textautogeneratequickaskwidget.h"
#include "widgets/instancesmanager/textautogeneratetextinstancesmanagerdialog.h"

#include "core/models/textautogeneratemessagesmodel.h"
#include "core/textautogeneratemanager.h"

#include "core/textautogeneratetextinstancesmanager.h"
#include "core/textautogeneratetextplugin.h"
#include "textautogeneratequickaskviewwidget.h"
#include "widgets/common/textautogeneratenotinstancefoundwidget.h"
#include "widgets/common/textautogeneratenotworkingwidget.h"
#include <QStackedWidget>
#include <QVBoxLayout>
using namespace TextAutoGenerateText;
using namespace Qt::Literals::StringLiterals;
TextAutoGenerateQuickAskWidget::TextAutoGenerateQuickAskWidget(TextAutoGenerateText::TextAutoGenerateManager *manager, QWidget *parent)
    : QWidget{parent}
    , mStackedWidget(new QStackedWidget(this))
    , mTextAutoGenerateQuickAskViewWidget(new TextAutoGenerateQuickAskViewWidget(manager, this))
    , mTextAutoGenerateNotWorkingWidget(new TextAutoGenerateNotWorkingWidget(manager, this))
    , mTextAutoGenerateNotInstanceFoundWidget(new TextAutoGenerateNotInstanceFoundWidget(this))
    , mManager(manager)
{
    auto mainLayout = new QVBoxLayout(this);
    mainLayout->setObjectName(u"mainLayout"_s);
    mainLayout->setContentsMargins({});

    mStackedWidget->setObjectName(u"mStackedWidget"_s);
    mainLayout->addWidget(mStackedWidget);

    mTextAutoGenerateQuickAskViewWidget->setObjectName(u"mTextAutoGenerateQuickAskViewWidget"_s);
    mStackedWidget->addWidget(mTextAutoGenerateQuickAskViewWidget);

    mTextAutoGenerateNotWorkingWidget->setObjectName(u"mTextAutoGenerateNotWorkingWidget"_s);
    mStackedWidget->addWidget(mTextAutoGenerateNotWorkingWidget);

    mTextAutoGenerateNotInstanceFoundWidget->setObjectName(u"mTextAutoGenerateNotInstanceFoundWidget"_s);
    mStackedWidget->addWidget(mTextAutoGenerateNotInstanceFoundWidget);

    connect(mTextAutoGenerateNotInstanceFoundWidget, &TextAutoGenerateNotInstanceFoundWidget::addInstanceRequested, this, [this]() {
        mTextAutoGenerateQuickAskViewWidget->slotConfigureInstances();
    });

    mStackedWidget->setCurrentWidget(mTextAutoGenerateQuickAskViewWidget);

    connect(mTextAutoGenerateNotWorkingWidget, &TextAutoGenerateNotWorkingWidget::ollamaStarted, this, [this]() {
        mStackedWidget->setCurrentWidget(mTextAutoGenerateQuickAskViewWidget);
    });

    connect(mTextAutoGenerateNotWorkingWidget,
            &TextAutoGenerateNotWorkingWidget::configureInstances,
            this,
            &TextAutoGenerateQuickAskWidget::slotConfigureInstances);

    connect(mTextAutoGenerateQuickAskViewWidget,
            &TextAutoGenerateQuickAskViewWidget::editingFinished,
            this,
            &TextAutoGenerateQuickAskWidget::slotEditingFinished2);

    connect(mTextAutoGenerateQuickAskViewWidget,
            &TextAutoGenerateQuickAskViewWidget::cancelRequested,
            this,
            &TextAutoGenerateQuickAskWidget::slotCancelRequest);

    connect(mTextAutoGenerateQuickAskViewWidget,
            &TextAutoGenerateQuickAskViewWidget::editMessageRequested,
            this,
            &TextAutoGenerateQuickAskWidget::slotEditMessage);

    connect(mTextAutoGenerateQuickAskViewWidget, &TextAutoGenerateQuickAskViewWidget::configureChanged, this, [this]() {
        updateCurrentPage();
    });
    connect(mTextAutoGenerateQuickAskViewWidget,
            &TextAutoGenerateQuickAskViewWidget::refreshAnswerRequested,
            this,
            &TextAutoGenerateQuickAskWidget::slotRefreshAnswer);

    if (mManager) {
        mPreviousSaveInDatabase = mManager->saveInDatabase();
        mManager->setSaveInDatabase(false);
        connect(mManager,
                &TextAutoGenerateManager::askMessageRequested,
                this,
                [this](const TextAutoGenerateText::TextAutoGenerateManager::AskMessageInfo &info) {
                    slotAskMessageRequester(info);
                });
    }
    loadEngine();
}

TextAutoGenerateQuickAskWidget::~TextAutoGenerateQuickAskWidget()
{
    if (mManager) {
        mManager->resetCurrentChatId();
        mManager->setSaveInDatabase(mPreviousSaveInDatabase);
    }
}

void TextAutoGenerateQuickAskWidget::slotEditMessage(const QModelIndex &index)
{
    const QByteArray uuid = index.data(TextAutoGenerateMessagesModel::UuidRole).toByteArray();
    const QString messageStr = index.data(TextAutoGenerateMessagesModel::OriginalMessageRole).toString();
    mTextAutoGenerateQuickAskViewWidget->editMessage(uuid, messageStr);
}

void TextAutoGenerateQuickAskWidget::slotAskMessageRequester(const TextAutoGenerateText::TextAutoGenerateManager::AskMessageInfo &info)
{
    if (!mPluginWasInitialized) {
        mAskMessageList.append(info);
    } else {
        slotEditingFinished(info, {});
    }
}

void TextAutoGenerateQuickAskWidget::updateCurrentPage()
{
    if (mManager->textAutoGenerateTextInstancesManager()->isEmpty()) {
        mStackedWidget->setCurrentWidget(mTextAutoGenerateNotInstanceFoundWidget);
    } else {
        mStackedWidget->setCurrentWidget(mTextAutoGenerateQuickAskViewWidget);
    }
}

void TextAutoGenerateQuickAskWidget::slotConfigureInstances()
{
    TextAutoGenerateTextInstancesManagerDialog dlg(mManager, this);
    if (dlg.exec()) {
        updateCurrentPage();
    }
}

void TextAutoGenerateQuickAskWidget::slotCancelRequest(const QByteArray &uuid)
{
    mManager->textAutoGeneratePlugin()->cancelRequest(uuid);
}

void TextAutoGenerateQuickAskWidget::slotRefreshAnswer(const QByteArray &chatId, const QModelIndex &index)
{
    const QByteArray uuid = index.data(TextAutoGenerateMessagesModel::UuidRole).toByteArray();
    const QString messageStr = index.data(TextAutoGenerateMessagesModel::OriginalMessageRole).toString();
    const TextAutoGenerateText::TextAutoGenerateTextPlugin::EditSendInfo info = {.message = messageStr,
                                                                                 .messageUuid = uuid,
                                                                                 .chatId = chatId,
                                                                                 .tools = {},
                                                                                 .attachmentInfoList = {}};
    mManager->textAutoGeneratePlugin()->editMessage(info);
}

void TextAutoGenerateQuickAskWidget::loadEngine()
{
    if (mManager) {
        connect(mManager, &TextAutoGenerateText::TextAutoGenerateManager::pluginsInitializedDone, this, &TextAutoGenerateQuickAskWidget::slotInitializeDone);
        connect(mManager, &TextAutoGenerateText::TextAutoGenerateManager::downloadErrorOccured, this, &TextAutoGenerateQuickAskWidget::slotAutogenerateFailed);
        connect(mManager, &TextAutoGenerateText::TextAutoGenerateManager::needToAddInstances, this, &TextAutoGenerateQuickAskWidget::slotNeedToAddInstances);
        mManager->loadEngine();
    }
}

void TextAutoGenerateQuickAskWidget::slotNeedToAddInstances()
{
    mStackedWidget->setCurrentWidget(mTextAutoGenerateNotInstanceFoundWidget);
}

void TextAutoGenerateQuickAskWidget::slotAutogenerateFailed(const QString &str)
{
    mTextAutoGenerateNotWorkingWidget->setMessageError(str);
    mStackedWidget->setCurrentWidget(mTextAutoGenerateNotWorkingWidget);
}

void TextAutoGenerateQuickAskWidget::slotInitializeDone()
{
    mPluginWasInitialized = true;
    for (const auto &info : std::as_const(mAskMessageList)) {
        slotEditingFinished(info, {});
    }
    mAskMessageList.clear();
}

void TextAutoGenerateQuickAskWidget::slotEditingFinished2(
    const QString &str,
    const QByteArray &messageUuid,
    const QList<QByteArray> &lstTools,
    const QList<TextAutoGenerateText::TextAutoGenerateAttachmentUtils::AttachmentElementInfo> &attachmentInfoList)
{
    mManager->checkCurrentChat();

    if (messageUuid.isEmpty()) {
        const TextAutoGenerateText::TextAutoGenerateTextPlugin::EditSendInfo sendInfo = {.message = str,
                                                                                         .messageUuid = {},
                                                                                         .chatId = mManager->currentChatId(),
                                                                                         .tools = lstTools,
                                                                                         .attachmentInfoList = attachmentInfoList};
        mManager->textAutoGeneratePlugin()->sendMessage(sendInfo);
    } else {
        const TextAutoGenerateText::TextAutoGenerateTextPlugin::EditSendInfo sendInfo = {.message = str,
                                                                                         .messageUuid = messageUuid,
                                                                                         .chatId = mManager->currentChatId(),
                                                                                         .tools = lstTools,
                                                                                         .attachmentInfoList = attachmentInfoList};
        mManager->textAutoGeneratePlugin()->editMessage(sendInfo);
    }
}

void TextAutoGenerateQuickAskWidget::slotEditingFinished(const TextAutoGenerateText::TextAutoGenerateManager::AskMessageInfo &info,
                                                         const QByteArray &messageUuid)
{
    mManager->checkCurrentChat();

    if (messageUuid.isEmpty()) {
        const TextAutoGenerateText::TextAutoGenerateTextPlugin::EditSendInfo sendInfo = {
            .message = info.message,
            .messageUuid = {},
            .chatId = mManager->currentChatId(),
            .tools = info.tools,
            .attachmentInfoList = TextAutoGenerateAttachmentUtils::createAttachmentElementInfoFromFileList(info.attachments)};
        mManager->textAutoGeneratePlugin()->sendMessage(sendInfo);
    } else {
        const TextAutoGenerateText::TextAutoGenerateTextPlugin::EditSendInfo sendInfo = {
            .message = info.message,
            .messageUuid = messageUuid,
            .chatId = mManager->currentChatId(),
            .tools = info.tools,
            .attachmentInfoList = TextAutoGenerateAttachmentUtils::createAttachmentElementInfoFromFileList(info.attachments)};
        mManager->textAutoGeneratePlugin()->editMessage(sendInfo);
    }
}

#include "moc_textautogeneratequickaskwidget.cpp"
