#include "VersionManager.h"
#include <QFileInfo>
#include <QRegularExpression>

#include "LoggerHelper.h"

AppVersionInfo VersionManager::getAppVersion(const QString &appName)
{
    AppVersionInfo info;
    QString linkPath = QString("/home/root/app_run/bin/%1").arg(appName);
    QFileInfo linkInfo(linkPath);

    if (!linkInfo.exists() || !linkInfo.isSymLink()) {
        LoggerHelper::instance()->warning(QString("[%1] The file does not exist or is a non-connected file.").arg(appName));
        return info;
    }

    QString targetPath = linkInfo.symLinkTarget();
    QFileInfo targetInfo(targetPath);
    QString targetBaseName = targetInfo.fileName();

    // 支持 app_CCU/app_TCU/app_PCU
    QRegularExpression re(QStringLiteral("%1_V(\\d+)R(\\d+)B(\\d+)").arg(appName));
    QRegularExpressionMatch match = re.match(targetBaseName);

    if (match.hasMatch()) {
        info.linkName = targetBaseName;
        info.major = match.captured(1).toInt();
        info.minor = match.captured(2).toInt();
        info.build = match.captured(3).toInt();
        info.success = true;
    }

    return info;
}

QString VersionManager::getHardwareVersion()
{
    QString linkPath = "/home/root/app_run/bin/HWVersion";
    QFileInfo linkInfo(linkPath);

    if (!linkInfo.exists() || !linkInfo.isSymLink()) {
        LoggerHelper::instance()->warning(QString("HWVersion The file does not exist or is a non-connected file."));
        return QString();
    }

    QString targetPath = linkInfo.symLinkTarget();
    QFileInfo targetInfo(targetPath);

    return targetInfo.fileName();
}
