/***************************************************************************
 * SPDX-FileCopyrightText: 2026 S. MANKOWSKI stephane@mankowski.fr
 * SPDX-License-Identifier: GPL-3.0-or-later
 ***************************************************************************/
#ifndef SKGASSISTANTPLUGINDOCKWIDGET_H
#define SKGASSISTANTPLUGINDOCKWIDGET_H
/** @file
 * A dock widget for the AI assistant plugin.
 */
#include <qjsonarray.h>
#include <qnetworkaccessmanager.h>
#include <qpointer.h>
#include <qurl.h>

#include "skgwidget.h"
#include "ui_skgassistantpluginwidget_dock.h"

class QJsonValue;
class QNetworkReply;

/**
 * A dock widget for the AI assistant plugin.
 */
class SKGAssistantPluginDockWidget : public SKGWidget
{
    Q_OBJECT

public:
    /**
     * Default Constructor
     * @param iParent the parent widget
     * @param iDocument the document
     */
    explicit SKGAssistantPluginDockWidget(QWidget *iParent, SKGDocument *iDocument);

    /**
     * Default Destructor
     */
    ~SKGAssistantPluginDockWidget() override;

private Q_SLOTS:
    void onAsk();
    void onClear();
    void onReplyFinished();
    void onUserPromptChanged();
    void onSaveCurrentAiSession();
    void onDeleteAiSession();
    void onAiSessionChanged(int iIndex);

private:
    Q_DISABLE_COPY(SKGAssistantPluginDockWidget)

    QUrl getCompletionEndpoint() const;
    void setBusy(bool iBusy);
    void refreshConversation() const;
    void refreshSessionsList(bool iSelectFirst = false) const;
    void slotRefreshSessionsList() const;
    void sendCompletionRequest();
    QString extractAssistantMessage(const QByteArray &iPayload, QString &oErrorMessage, bool &oNeedsFollowUp);
    QString executeToolCall(const QJsonObject &iToolCall) const;
    QString executeSqliteSelect(const QString &iSql) const;
    QString executeWebSearch(const QString &iQuery, int iMaxResults) const;
    QString executeGetCurrentSelection() const;
    static QJsonArray getTools();
    static QJsonArray getRequestMessages(const QJsonArray &iMessages);
    static QString sqlResultToJson(const SKGStringListList &iResult);
    static QString contentToText(const QJsonValue &iContent);
    static QString extractReasoningFromContent(QString &ioContent);
    static QString reasoningContentToText(const QJsonObject &iMessage, const QJsonObject &iChoice);
    static QString getSystemPrompt();
    static QString markdownToHtml(const QString &iContent);

    Ui::skgassistantplugin_dock ui{};
    QNetworkAccessManager m_networkManager;
    QPointer<QNetworkReply> m_pendingReply;
    QJsonArray m_messages;
    QString m_pendingReasoningContent;
    int m_toolCallDepth = 0;
};

#endif // SKGASSISTANTPLUGINDOCKWIDGET_H
