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

#include "Graph/Nodes/InworldNode_RandomCannedText.h"

#include "Async/Async.h"
#include "Dom/JsonObject.h"
#include "Graph/InworldGraph.h"
#include "Misc/TVariant.h"
#include "Policies/PrettyJsonPrintPolicy.h"
#include "Serialization/JsonReader.h"
#include "Serialization/JsonSerializer.h"

UInworldNode_RandomCannedText::UInworldNode_RandomCannedText()
{
	NodeName = "Random Canned Text";
	bIsGetter = true;
}

UInworldNode_RandomCannedText* UInworldNode_RandomCannedText::CreateNative(
	class UObject* Outer, const FString& NodeName, const TArray<FString>& CannedPhrases)
{
	UInworldNode_RandomCannedText* NewNode = NewObject<UInworldNode_RandomCannedText>(Outer, FName(NodeName));
	NewNode->NodeName = NodeName;
	NewNode->CannedPhrases = CannedPhrases;
	return NewNode;
}

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

	// execution_config
	{
		TSharedPtr<FJsonObject> ExecCfg = MakeShared<FJsonObject>();
		ExecCfg->SetStringField(TEXT("type"), TEXT("RandomCannedTextNodeExecutionConfig"));

		TSharedPtr<FJsonObject> Props = MakeShared<FJsonObject>();
		TArray<TSharedPtr<FJsonValue>> Phrases;
		Phrases.Reserve(CannedPhrases.Num());
		for (const FString& Phrase : CannedPhrases)
		{
			Phrases.Add(MakeShared<FJsonValueString>(Phrase));
		}
		Props->SetArrayField(TEXT("canned_phrases"), Phrases);
		ExecCfg->SetObjectField(TEXT("properties"), Props);
		NodeObj->SetObjectField(TEXT("execution_config"), ExecCfg);
	}

	// Append to main.nodes
	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);

	return EInworldRuntimeErrors::SUCCESS;
}
