// Copyright Epic Games, Inc. All Rights Reserved.

#include "RuntimeSpeechRecognizerVosk.h"
#include "Misc/EngineVersionComparison.h"
#include "Interfaces/IPluginManager.h"
#include "Misc/Paths.h"
#include "HAL/PlatformProcess.h"

#define LOCTEXT_NAMESPACE "FRuntimeSpeechRecognizerVoskModule"

void FRuntimeSpeechRecognizerVoskModule::StartupModule()
{
#if PLATFORM_WINDOWS
	const FString PluginDir = IPluginManager::Get().FindPlugin("RuntimeSpeechRecognizerVosk")->GetBaseDir();
#if UE_VERSION_OLDER_THAN(5, 8, 0)
	const FString VoskSharedLibFilePath = FPaths::Combine(PluginDir, TEXT("Source"), TEXT("RuntimeSpeechRecognizerVosk"), TEXT(PREPROCESSOR_TO_STRING(VOSK_SHAREDLIB_PATH)));
#else
	const FString VoskSharedLibFilePath = FPaths::Combine(PluginDir, TEXT("Source"), TEXT("RuntimeSpeechRecognizerVosk"), TEXT(UE_STRINGIZE(VOSK_SHAREDLIB_PATH)));
#endif
	const FString VoskSharedLibDirPath = FPaths::GetPath(VoskSharedLibFilePath);

	UE_LOG(LogRuntimeSpeechRecognizerVosk, Log, TEXT("Loading Vosk dynamic/shared library from '%s'"), *VoskSharedLibFilePath);

	FPlatformProcess::PushDllDirectory(*VoskSharedLibDirPath);
	VoskSharedLibHandle = FPlatformProcess::GetDllHandle(*VoskSharedLibFilePath);
	FPlatformProcess::PopDllDirectory(*VoskSharedLibDirPath);

	if (!VoskSharedLibHandle)
	{
		UE_LOG(LogRuntimeSpeechRecognizerVosk, Fatal, TEXT("Failed to load Vosk"));
	}
#endif
}

void FRuntimeSpeechRecognizerVoskModule::ShutdownModule()
{
#if PLATFORM_WINDOWS
	if (VoskSharedLibHandle != nullptr)
	{
		FPlatformProcess::FreeDllHandle(VoskSharedLibHandle);
		VoskSharedLibHandle = nullptr;
	}
#endif
}

#undef LOCTEXT_NAMESPACE
	
IMPLEMENT_MODULE(FRuntimeSpeechRecognizerVoskModule, RuntimeSpeechRecognizerVosk)

DEFINE_LOG_CATEGORY(LogRuntimeSpeechRecognizerVosk);