// Copyright 2022-2025 Theai, Inc. dba Inworld AI

#include "InworldLipsync.h"
#include "Misc/MessageDialog.h"
#include "Modules/ModuleManager.h"
#include "Interfaces/IPluginManager.h"
#include "Misc/Paths.h"
#include "HAL/PlatformProcess.h"


#define LOCTEXT_NAMESPACE "FInworldLipsyncModule"

DEFINE_LOG_CATEGORY(LogInworldLipsync);

void FInworldLipsyncModule::StartupModule()
{
	const FString PluginBaseDir{IPluginManager::Get().FindPlugin(TEXT("InworldLipsync"))->GetBaseDir()};
	const FString BinariesSubdirectory{FPlatformProcess::GetBinariesSubdirectory()};
	const FString DllPath{FPaths::Combine(PluginBaseDir, "Binaries", BinariesSubdirectory)};

	FPlatformProcess::PushDllDirectory(*DllPath);
#if PLATFORM_WINDOWS
	PocketSphinxDllHandle = FPlatformProcess::GetDllHandle(*FPaths::Combine(DllPath, "pocketsphinx.dll"));
#elif PLATFORM_LINUX
	PocketSphinxDllHandle = FPlatformProcess::GetDllHandle(*FPaths::Combine(DllPath, "libpocketsphinx.so"));
#elif PLATFORM_MAC
	PocketSphinxDllHandle = FPlatformProcess::GetDllHandle(*FPaths::Combine(DllPath, "libpocketsphinx.dylib"));
#endif
	FPlatformProcess::PopDllDirectory(*DllPath);

	if (PocketSphinxDllHandle == nullptr)
	{
		UE_LOG(LogInworldLipsync, Error, TEXT("Failed to load pocketsphinx shared lib."))
		return;
	}
}

void FInworldLipsyncModule::ShutdownModule()
{
	// Free the dll handle
	if (PocketSphinxDllHandle)
	{
		FPlatformProcess::FreeDllHandle(PocketSphinxDllHandle);
		PocketSphinxDllHandle = nullptr;
	}
}

#undef LOCTEXT_NAMESPACE

IMPLEMENT_MODULE(FInworldLipsyncModule, InworldLipsync)
