#include "version.hh"
#include <QFile>
#include <QRegularExpression>

namespace Version {
QString version()
{
  QFile versionFile( ":/version.txt" );

  if ( !versionFile.open( QFile::ReadOnly ) ) {
    return QStringLiteral( "[Unknown Version]" );
  }
  else {
    return versionFile.readAll().trimmed();
  }
}

QString everything()
{
  return QStringLiteral( R"(Version: %1
Qt %2 %3
%4 %5 %6 %7
Flags: %8)" )
    .arg( Version::version() )
    .arg( QLatin1String( qVersion() ), Version::compiler )
    .arg( QSysInfo::productType(), QSysInfo::kernelType(), QSysInfo::kernelVersion(), QSysInfo::buildAbi() )
    .arg( flags );
}

QString getVersionTag()
{
  QString ver = version();

  // version.txt format (generated by CMake):
  // Format 1 (Git repo): "26.7.0-abc12345678 (branch-name) at 2024-01-15T10:30:00UTC"
  // Format 2 (Non-Git):   "26.7.0 at 2024-01-15T10:30:00UTC"
  // Format 3 (Fallback):  "26.7.0"

  // Match Format 1: version-hash (branch) at ...
  QRegularExpression re( R"(^([\d.]+)-([a-f0-9]+)\s*\([^)]+\)\s+at)" );
  QRegularExpressionMatch match = re.match( ver );

  if ( match.hasMatch() ) {
    QString baseVersion = match.captured( 1 ); // e.g. "26.7.0"
    QString gitHash     = match.captured( 2 ); // e.g. "abc12345678"

    return QStringLiteral( "v%1_alpha.%2" ).arg( baseVersion, gitHash ); // e.g. "v26.7.0_alpha.abc12345678"
  }

  // Match Format 2: version at ... (no git hash)
  QRegularExpression reSimple( R"(^([\d.]+)\s+at)" );
  QRegularExpressionMatch matchSimple = reSimple.match( ver );

  if ( matchSimple.hasMatch() ) {
    return QStringLiteral( "v%1" ).arg( matchSimple.captured( 1 ) ); // e.g. "v26.7.0"
  }

  // Match Format 3: just version number
  QRegularExpression reNoAt( R"(^([\d.]+))" );
  QRegularExpressionMatch matchNoAt = reNoAt.match( ver );

  if ( matchNoAt.hasMatch() ) {
    return QStringLiteral( "v%1" ).arg( matchNoAt.captured( 1 ) ); // e.g. "v26.7.0"
  }

  return QString();
}

QString getReleaseUrl()
{
  QString tag = getVersionTag();
  if ( tag.isEmpty() ) {
    return QStringLiteral( "https://github.com/xiaoyifang/goldendict-ng/releases" );
  }
  return QStringLiteral( "https://github.com/xiaoyifang/goldendict-ng/releases/tag/%1" ).arg( tag );
}

} // namespace Version
