#include "mcpserveritem.h"
#include <localmodelserver.h>

#include <DFontSizeManager>
#include <DGuiApplicationHelper>
#include <DPalette>
#include <DDialog>

#include <QHBoxLayout>
#include <QVBoxLayout>
#include <QLoggingCategory>
#include <QtConcurrent>

using namespace uos_ai;

Q_DECLARE_LOGGING_CATEGORY(logAIGUI)

static constexpr int TIMER_BEGIN = 720; // 5秒轮询状态60分钟

McpServerItem::McpServerItem(DWidget *parent)
    : DWidget(parent)
    , m_pProcess(new QProcess(this))
{
    m_timer = new QTimer(this);
    m_timer->setInterval(5000);

    initUI();
    initConnect();
    checkInstallStatus();
}

McpServerItem::~McpServerItem()
{
    if (m_pProcess) {
        m_pProcess->terminate();
    }
    m_timer->stop();
}

void McpServerItem::initUI()
{
    // 左侧信息区域
    QVBoxLayout *infoLayout = new QVBoxLayout();
    infoLayout->setContentsMargins(0, 0, 0, 0);
    infoLayout->setSpacing(2);

    m_pNameLabel = new DLabel();
    DFontSizeManager::instance()->bind(m_pNameLabel, DFontSizeManager::T6, QFont::Medium);

    m_pDescLabel = new DLabel();
    DFontSizeManager::instance()->bind(m_pDescLabel, DFontSizeManager::T8, QFont::Normal);
    m_pDescLabel->setElideMode(Qt::ElideRight);

    infoLayout->addWidget(m_pNameLabel);
    infoLayout->addWidget(m_pDescLabel);

    // 右侧控制区域
    QHBoxLayout *controlLayout = new QHBoxLayout();
    controlLayout->setContentsMargins(0, 0, 0, 0);
    controlLayout->setSpacing(10);

    // 安装相关按钮
    m_pBtnInstall = new DSuggestButton(tr("Install"));
    m_pBtnInstall->setFixedHeight(30);
    m_pBtnInstall->setMinimumWidth(70);
    m_pBtnInstall->setMaximumWidth(80);

    m_pBtnUninstall = new DPushButton(tr("Uninstall"));
    m_pBtnUninstall->setFixedHeight(30);
    m_pBtnUninstall->setMinimumWidth(70);
    m_pBtnUninstall->setMaximumWidth(100);
    m_pBtnUninstall->hide();

    // 更新按钮
    m_pBtnUpdate = new DSuggestButton(tr("Update"));
    m_pBtnUpdate->setFixedHeight(30);
    m_pBtnUpdate->setMinimumWidth(70);
    m_pBtnUpdate->setMaximumWidth(90);
    m_pBtnUpdate->hide();

    controlLayout->addWidget(m_pBtnInstall);
    controlLayout->addWidget(m_pBtnUninstall);
    controlLayout->addWidget(m_pBtnUpdate);

    QHBoxLayout *mainLayout = new QHBoxLayout(this);
    mainLayout->setContentsMargins(10, 10, 10, 10);
    mainLayout->setSpacing(10);
    mainLayout->addLayout(infoLayout);
    mainLayout->addStretch();
    mainLayout->addLayout(controlLayout);
}

void McpServerItem::initConnect()
{
    connect(m_pBtnInstall, &DSuggestButton::clicked, this, &McpServerItem::onInstall);
    connect(m_pBtnUninstall, &DPushButton::clicked, this, &McpServerItem::onUninstall);
    connect(m_pBtnUpdate, &DSuggestButton::clicked, this, &McpServerItem::onUpdate);
    connect(m_timer, &QTimer::timeout, this, &McpServerItem::checkStatusOntime);
}

void McpServerItem::setText(const QString &theme, const QString &summary)
{
    m_pNameLabel->setText(theme);
    m_pDescLabel->setText(summary);
    m_pDescLabel->setToolTip(summary);
}

void McpServerItem::setAppName(const QString &appName)
{
    m_appName = appName;
}

void McpServerItem::updateStatus()
{
    checkInstallStatus();
}

void McpServerItem::onInstall()
{
    qCDebug(logAIGUI) << "Install MCP server clicked. AppName:" << m_appName;

    if (m_appName.isEmpty())
        return;

    // 调用应用商店
    LocalModelServer::getInstance().openInstallWidget(m_appName);
    beginTimer(TIMER_BEGIN);
}

void McpServerItem::onUninstall()
{
    qCDebug(logAIGUI) << "Uninstall MCP server clicked. AppName:" << m_appName;

    if (m_appName.isEmpty()) {
        qCWarning(logAIGUI) << "App name is empty!!!";
        return;
    }

    // 调用应用商店
    LocalModelServer::getInstance().openManagerWidget();
    beginTimer(TIMER_BEGIN);
}

void McpServerItem::onUpdate()
{
    qCDebug(logAIGUI) << "Update button clicked. AppName:" << m_appName;
    if (m_appName.isEmpty())
        return;
    // 可直接调用安装逻辑
    LocalModelServer::getInstance().openInstallWidget(m_appName);
    beginTimer(TIMER_BEGIN);
}

void McpServerItem::checkUpdateStatus()
{
    if (!m_isInstalled) {
        m_pBtnUpdate->hide();
        return;
    }

    QFuture<void> future = QtConcurrent::run([=]() {
        QProcess process;
        process.start("apt", QStringList() << "list" << "--upgradable");
        process.waitForFinished();
        QByteArray reply = process.readAllStandardOutput();
        QString updateVersion = getUpdateVersion(reply);
        QMetaObject::invokeMethod(this, [this, updateVersion]() {
            if (!updateVersion.isEmpty()) {
                m_updateVersion = updateVersion;
                m_pBtnUpdate->show();
            } else {
                m_updateVersion.clear();
                m_pBtnUpdate->hide();
            }
            //qCInfo(logAIGUI) << "AppName:" << m_appName << "upgradable version:" << m_updateVersion;
        }, Qt::QueuedConnection);
        process.deleteLater();
    });
}

QString McpServerItem::getUpdateVersion(const QByteArray& reply)
{
    QString output = QString::fromUtf8(reply);
    QStringList lines = output.split('\n');
    for (const QString& line : lines) {
        if (line.contains(m_appName)) {
            QStringList parts = line.split('/');
            if (parts.size() > 1) {
                QString versionPart = parts[1];
                QStringList versionInfo = versionPart.split(' ');
                if (versionInfo.size() > 1) {
                    return versionInfo[1].trimmed();
                }
            }
        }
    }

    return "";
}

void McpServerItem::checkInstallStatus()
{
    if (!m_pProcess->atEnd()) {
        return;
    }

    if (m_pProcess->state() == QProcess::Running) {
        m_pProcess->waitForFinished();
    }

    m_pProcess->start("dpkg-query", QStringList() << "-W" << QString("-f='${db:Status-Status}\n'") << m_appName);
    m_pProcess->waitForFinished();
    QByteArray reply = m_pProcess->readAllStandardOutput();
    bool newInstallStatus = (reply == "'installed\n'");

    if (m_isInstalled != newInstallStatus) {
        qCInfo(logAIGUI) << "MCP server install status changed. AppName:" << m_appName << ", Installed:" << newInstallStatus;
        m_isInstalled = newInstallStatus;
        LocalModelServer::getInstance().localModelStatusChanged(m_appName, m_isInstalled);
        changeInstallStatus();
        return;
    }

    checkUpdateStatus();
}

void McpServerItem::checkStatusOntime()
{
    if (m_timerCount > 0) {
        checkInstallStatus();
        --m_timerCount;
    } else {
        m_timerCount = 0;
        m_timer->stop();
    }
}

void McpServerItem::beginTimer(const int &time)
{
    qCDebug(logAIGUI) << "Begin timer for MCP server. Time:" << time;
    m_timerCount = time;
    m_timer->start();
}

void McpServerItem::stopTimer()
{
    qCDebug(logAIGUI) << "Stop timer for MCP server.";
    m_timerCount = 0;
    m_timer->stop();
}

void McpServerItem::changeInstallStatus()
{
    if (m_isInstalled) {
        m_pBtnInstall->hide();
        m_pBtnUninstall->show();
    } else {
        m_pBtnUninstall->hide();
        m_pBtnInstall->show();
    }
    checkUpdateStatus();
}
