#include "mcpserverwidget.h"
#include "themedlable.h"
#include "mcpserveritem.h"

#include <DLabel>
#include <DFontSizeManager>
#include <DBackgroundGroup>
#include <DGuiApplicationHelper>
#include <DPushButton>
#include <DCommandLinkButton>

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

using namespace uos_ai;

Q_DECLARE_LOGGING_CATEGORY(logAIGUI)

static const QString MCP_APP("uos-ai-agent");

McpServerWidget::McpServerWidget(DWidget *parent)
    : DWidget(parent)
{
    initUI();
    onThemeTypeChanged();
    connect(DGuiApplicationHelper::instance(), &DGuiApplicationHelper::themeTypeChanged, this, &McpServerWidget::onThemeTypeChanged);
}

void McpServerWidget::initUI()
{
    QVBoxLayout *layout = new QVBoxLayout(this);
    layout->setContentsMargins(0, 0, 0, 0);
    layout->setSpacing(10);

    // 标题
    m_pWidgetLabel = new ThemedLable(getTitleName());
    m_pWidgetLabel->setPaletteColor(QPalette::Text, DPalette::TextTitle);
    DFontSizeManager::instance()->bind(m_pWidgetLabel, DFontSizeManager::T5, QFont::Bold);
    layout->addWidget(m_pWidgetLabel, 0, Qt::AlignLeft);

    // 服务组件
    layout->addWidget(serverWidget());
    layout->addStretch();
}

QString McpServerWidget::getTitleName()
{
    return tr("MCP Server");
}

void McpServerWidget::updateStatus()
{
    qCDebug(logAIGUI) << "Updating MCP server status";
    // 更新MCP服务状态
    if (m_pServerItem) {
        m_pServerItem->updateStatus();
    }
}

void McpServerWidget::onThemeTypeChanged()
{
    // 主题切换处理
    qCDebug(logAIGUI) << "MCP server widget theme changed";

    // 设置DBackgroundGroup的背景色
    if (m_pServerWidget) {
        DPalette pl = m_pServerWidget->palette();
        pl.setColor(DPalette::Base, DGuiApplicationHelper::instance()->applicationPalette().color(DPalette::ItemBackground));
        m_pServerWidget->setPalette(pl);
    }
}

DBackgroundGroup *McpServerWidget::serverWidget()
{
    qCDebug(logAIGUI) << "Creating MCP server widget";

    m_pServerItem = new McpServerItem(this);
    m_pServerItem->setText(tr("Install UOS AI Agent"), 
                           tr("After installation, MCP Server will be available."));
    m_pServerItem->setAppName(MCP_APP);
    m_pServerItem->setMinimumHeight(60);
    m_pServerItem->setMaximumHeight(75);

    QHBoxLayout *bgLayout = new QHBoxLayout;
    bgLayout->setContentsMargins(0, 0, 0, 0);
    bgLayout->addWidget(m_pServerItem);

    m_pServerWidget = new DBackgroundGroup(bgLayout, this);
    m_pServerWidget->setContentsMargins(0, 0, 0, 0);

    return m_pServerWidget;
}
