// Georgy Treshchev 2026 All Rights Reserved.

#pragma once

#include "CoreMinimal.h"
#include "Modules/ModuleManager.h"
#include "RuntimeVoskModelTypes.h"
#include "SpeechRecognizerDownloader.h"

DECLARE_LOG_CATEGORY_EXTERN(LogRuntimeSpeechRecognizerVoskEditor, Log, All);

/**
 * Editor module for the Runtime Speech Recognizer Vosk extension plugin.
 * Provides a Project Settings panel for browsing, downloading, and deleting Vosk models
 */
class FRuntimeSpeechRecognizerVoskEditorModule : public IModuleInterface
{
public:
	virtual void StartupModule() override;
	virtual void ShutdownModule() override;

	/** Ensures the Vosk models directory is staged as NonUFS so extracted model files are included when packaging */
	bool UpdatePackagingSettings() const;

	/** Begins downloading and extracting the given model. Progress/completion are reported via the delegates below */
	void DownloadModel(const FVoskModelVariant& ModelVariant);

	/** Cancels an in-progress download for the given model */
	void CancelDownloadModel(const FString& ModelId);

	/** True if the given model is currently downloading/extracting */
	bool IsDownloadActive(const FString& ModelId) const;

	/** Deletes a model's extracted files from disk */
	bool DeleteModel(const FString& ModelId);

	DECLARE_MULTICAST_DELEGATE_TwoParams(FOnModelDownloadProgress, const FString& /* ModelId */, float /* Progress 0..1 */);
	DECLARE_MULTICAST_DELEGATE_OneParam(FOnModelDownloadComplete, const FString& /* ModelId */);
	DECLARE_MULTICAST_DELEGATE_OneParam(FOnModelDownloadCanceled, const FString& /* ModelId */);
	DECLARE_MULTICAST_DELEGATE_TwoParams(FOnModelOperationFailed, const FString& /* ModelId */, const FText& /* ErrorMessage */);

	FOnModelDownloadProgress OnModelDownloadProgress;
	FOnModelDownloadComplete OnModelDownloadComplete;
	FOnModelDownloadCanceled OnModelDownloadCanceled;
	FOnModelOperationFailed OnModelOperationFailed;

private:
	/** ModelId -> active downloader. Presence in this map is what "is downloading" means */
	TMap<FString, TSharedPtr<FRuntimeChunkDownloader_Recognizer>> DownloadTasks;

	/** Extracts a downloaded .zip archive (on disk at ZipFilePath) into the Vosk models directory */
	bool ExtractModelZip(const FString& ZipFilePath, const FString& ModelId, FText& OutError) const;
};