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

#include "Graph/Nodes/InworldNode_KeywordMatcher.h"

#include "Dom/JsonObject.h"
#include "Serialization/JsonSerializer.h"

UInworldNode_KeywordMatcher::UInworldNode_KeywordMatcher()
{
	NodeName = "Keyword Matcher";
}

EInworldRuntimeErrors UInworldNode_KeywordMatcher::GetJsonConfig(const TSharedRef<FJsonObject>& GraphJson)
{
	TSharedPtr<FJsonObject> NodeObj = MakeShared<FJsonObject>();
	NodeObj->SetStringField(TEXT("id"), GetNodeName());
	NodeObj->SetStringField(TEXT("type"), TEXT("KeywordMatcherNode"));

	TSharedPtr<FJsonObject> Main = GraphJson->GetObjectField(TEXT("main"));
	TArray<TSharedPtr<FJsonValue>> Nodes = Main->GetArrayField(TEXT("nodes"));
	Nodes.Add(MakeShared<FJsonValueObject>(NodeObj));
	Main->SetArrayField(TEXT("nodes"), Nodes);

	// creation_config
	{
		TSharedPtr<FJsonObject> CreateCfg = MakeShared<FJsonObject>();
		{
			TSharedPtr<FJsonObject> CreateProps = MakeShared<FJsonObject>();
			{
				TArray<TSharedPtr<FJsonValue>> KeywordGroups;
				for (const FInworldKeywordGroup& KeywordGroup : CreationConfig.KeywordGroups)
				{
					TSharedPtr<FJsonObject> KeywordGroupObj = MakeShared<FJsonObject>();
					KeywordGroupObj->SetStringField(TEXT("name"), KeywordGroup.Name);
					TArray<TSharedPtr<FJsonValue>> Keywords;
					for (const FString& Keyword : KeywordGroup.Keywords)
					{
						Keywords.Add(MakeShared<FJsonValueString>(Keyword));
					}
					KeywordGroupObj->SetArrayField(TEXT("keywords"), Keywords);
					KeywordGroups.Add(MakeShared<FJsonValueObject>(KeywordGroupObj));
				}

				CreateProps->SetArrayField(TEXT("keyword_groups"), KeywordGroups);
			}
			CreateCfg->SetObjectField(TEXT("properties"), CreateProps);
		}
		CreateCfg->SetStringField(TEXT("type"), TEXT("KeywordMatcherNodeCreationConfig"));
		NodeObj->SetObjectField(TEXT("creation_config"), CreateCfg);
	}

	return EInworldRuntimeErrors::SUCCESS;
}
