/* SPDX-FileCopyrightText: 2026 Project Tick
 * SPDX-FileContributor: Project Tick
 * SPDX-License-Identifier: GPL-3.0-or-later WITH LicenseRef-MeshMC-MMCO-Module-Exception-1.0
 *
 *   MeshMC - A Custom Launcher for Minecraft
 *   Copyright (C) 2026 Project Tick
 *
 *   This program is free software: you can redistribute it and/or modify
 *   it under the terms of the GNU General Public License as published by
 *   the Free Software Foundation, either version 3 of the License, or
 *   (at your option) any later version, with the additional permission
 *   described in the MeshMC MMCO Module Exception 1.0.
 *
 *   This program is distributed in the hope that it will be useful,
 *   but WITHOUT ANY WARRANTY; without even the implied warranty of
 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *   GNU General Public License for more details.
 *
 *   You should have received a copy of the GNU General Public License
 *   along with this program.  If not, see <https://www.gnu.org/licenses/>.
 *
 *   You should have received a copy of the MeshMC MMCO Module Exception 1.0
 *   along with this program.  If not, see <https://projecttick.org/licenses/>.
 *
 */

#include "ContentDownloadTask.h"
#include "Application.h"
#include "minecraft/mod/ModMetadataIndex.h"
#include "net/Download.h"
#include "net/ChecksumValidator.h"

#include <QDateTime>
#include <QDir>
#include <QFile>
#include <QFileInfo>
#include <QCryptographicHash>

ContentDownloadTask::ContentDownloadTask(
	const QList<ModPlatform::DownloadItem>& items, const QString& targetDir,
	QObject* parent)
	: Task(parent), m_items(items), m_targetDir(targetDir)
{
}

void ContentDownloadTask::setMetadataIndex(
	std::shared_ptr<ModMetadataIndex> index)
{
	m_metadata = std::move(index);
}

void ContentDownloadTask::executeTask()
{
	if (m_items.isEmpty()) {
		emitSucceeded();
		return;
	}

	QDir dir(m_targetDir);
	if (!dir.exists()) {
		dir.mkpath(".");
	}

	setStatus(tr("Downloading %1 file(s)...").arg(m_items.size()));

	m_netJob = new NetJob("ContentDownload", APPLICATION->network());

	int skipped = 0;
	for (const auto& item : m_items) {
		QString targetPath = dir.filePath(item.fileName);

		// Updates explicitly target a different on-disk file ("foo-1.0.jar"
		// -> "foo-1.1.jar"). Drop the old file (and its sidecar) before
		// downloading so the directory never holds both versions at once.
		if (!item.replacesFileName.isEmpty() &&
			item.replacesFileName != item.fileName) {
			const QString oldEnabled = dir.filePath(item.replacesFileName);
			const QString oldDisabled =
				oldEnabled + QStringLiteral(".disabled");
			for (const QString& candidate : {oldEnabled, oldDisabled}) {
				if (QFile::exists(candidate)) {
					if (QFile::remove(candidate)) {
						qDebug() << "ContentDownload: removed superseded"
								 << candidate;
					} else {
						qWarning()
							<< "ContentDownload: failed to remove" << candidate;
					}
				}
			}
			if (m_metadata) {
				m_metadata->remove(item.replacesFileName);
			}
		}

		// Skip if file already exists with matching SHA1 checksum and the
		// caller did not request a forced replace.
		if (!item.replaceExisting && QFileInfo::exists(targetPath) &&
			!item.sha1.isEmpty()) {
			QFile existingFile(targetPath);
			if (existingFile.open(QIODevice::ReadOnly)) {
				QCryptographicHash hash(QCryptographicHash::Sha1);
				hash.addData(&existingFile);
				existingFile.close();
				if (hash.result().toHex() == item.sha1.toLatin1().toLower()) {
					qDebug() << "Skipping" << item.fileName
							 << "- already exists with matching SHA1";
					skipped++;
					continue;
				}
			}
		}

		// A forced replace must clear the destination first so the
		// downloader writes a fresh file rather than appending or failing.
		if (item.replaceExisting && QFileInfo::exists(targetPath)) {
			if (!QFile::remove(targetPath)) {
				qWarning() << "ContentDownload: cannot replace" << targetPath;
			}
			if (m_metadata) {
				m_metadata->remove(item.fileName);
			}
		}

		auto dl = Net::Download::makeFile(QUrl(item.downloadUrl), targetPath);
		if (!item.sha1.isEmpty()) {
			dl->addValidator(new Net::ChecksumValidator(
				QCryptographicHash::Sha1,
				QByteArray::fromHex(item.sha1.toLatin1())));
		}
		m_netJob->addNetAction(dl);
	}

	if (skipped > 0) {
		qDebug() << "Skipped" << skipped << "already-existing file(s)";
	}

	// If all files were skipped, nothing to download
	if (m_netJob->size() == 0) {
		m_netJob.reset();
		writeSidecars();
		emitSucceeded();
		return;
	}

	connect(m_netJob.get(), &NetJob::succeeded, this,
			&ContentDownloadTask::onDownloadSucceeded);
	connect(m_netJob.get(), &NetJob::failed, this,
			&ContentDownloadTask::onDownloadFailed);
	connect(m_netJob.get(), &NetJob::progress, this,
			&ContentDownloadTask::onDownloadProgress);

	m_netJob->start();
}

void ContentDownloadTask::writeSidecars()
{
	if (!m_metadata) {
		return;
	}
	const QDir dir(m_targetDir);
	for (const auto& item : m_items) {
		// We only persist sidecars for items that finished on disk and that
		// we can reason about later. Pure-local installs are recorded by
		// ModFolderModel::installMod directly.
		const QString path = dir.filePath(item.fileName);
		if (!QFile::exists(path)) {
			continue;
		}

		ModMetadataIndex::Entry e;
		e.fileName = item.fileName;
		e.platform = item.platform;
		e.projectId = item.projectId;
		e.versionId = item.versionId;
		e.name = item.name;
		e.slug = QString();
		e.downloadUrl = item.downloadUrl;
		e.sha1 = item.sha1.toLower();
		e.fileSize = item.fileSize;
		e.isDependency = item.isDependency;
		e.installedAt = QDateTime::currentDateTimeUtc();
		m_metadata->put(e);
	}
}

void ContentDownloadTask::onDownloadSucceeded()
{
	m_netJob.reset();
	writeSidecars();
	emitSucceeded();
}

void ContentDownloadTask::onDownloadFailed(QString reason)
{
	m_netJob.reset();
	emitFailed(reason);
}

void ContentDownloadTask::onDownloadProgress(qint64 current, qint64 total)
{
	setProgress(current, total);
}
