// Copyright HyperTwist, Inc. All Rights Reserved.

#include "Misc/AutomationTest.h"

#include "Engine/GameInstance.h"
#include "HyperTwistTraining/HyperTwistTrainingSubsystem.h"
#include "UObject/UnrealType.h"

#if WITH_AUTOMATION_TESTS

namespace HyperTwistQbrPhase6RANTestInternal
{
	FHyperTwistTrainingDeck MakeRecognitionDeck()
	{
		FHyperTwistTrainingDeck Deck;
		Deck.DeckId = TEXT("phase6r-an/qbr-locale-presentation");
		Deck.Title = TEXT("Phase 6R-AN Qbr Locale Presentation");
		Deck.DeliveryModes = {
			EHyperTwistTrainingDeliveryMode::RecognitionAssisted,
			EHyperTwistTrainingDeliveryMode::CoachReviewed
		};

		FHyperTwistTrainingCase TrainingCase;
		TrainingCase.CaseId = TEXT("phase6r-an-case");
		TrainingCase.PuzzleId = TEXT("cube/3x3x3");
		TrainingCase.PromptKind = EHyperTwistTrainingPromptKind::Recognition;
		TrainingCase.PromptLabel = TEXT("Phase 6R-AN Recognition");
		TrainingCase.AllowedDeliveryModes = {
			EHyperTwistTrainingDeliveryMode::RecognitionAssisted,
			EHyperTwistTrainingDeliveryMode::CoachReviewed
		};
		Deck.Cases = {TrainingCase};
		return Deck;
	}

	void ForceMockRecognitionClient(UHyperTwistTrainingSubsystem* TrainingSubsystem)
	{
		if (TrainingSubsystem == nullptr)
		{
			return;
		}

		if (FStrProperty* RecognitionClientKindProperty = FindFProperty<FStrProperty>(
			UHyperTwistTrainingSubsystem::StaticClass(),
			TEXT("RecognitionClientKind")
		))
		{
			RecognitionClientKindProperty->SetPropertyValue_InContainer(TrainingSubsystem, TEXT("mock"));
		}
	}

	UHyperTwistTrainingSubsystem* MakeRecognitionSubsystem(const FString& SessionId)
	{
		UGameInstance* GameInstance = NewObject<UGameInstance>();
		if (GameInstance == nullptr)
		{
			return nullptr;
		}

		UHyperTwistTrainingSubsystem* TrainingSubsystem = NewObject<UHyperTwistTrainingSubsystem>(GameInstance);
		if (TrainingSubsystem == nullptr)
		{
			return nullptr;
		}

		ForceMockRecognitionClient(TrainingSubsystem);
		const FHyperTwistTrainingRunState RunState = TrainingSubsystem->StartTrainingRunFromDeck(
			MakeRecognitionDeck(),
			TEXT("phase6r-an-user"),
			SessionId,
			EHyperTwistTrainingDeliveryMode::RecognitionAssisted
		);
		return RunState.IsStructurallyValid() ? TrainingSubsystem : nullptr;
	}

	void SubmitPreviewFrame(
		UHyperTwistTrainingSubsystem* TrainingSubsystem,
		const FString& FaceId,
		const int32 FrameOrdinal
	)
	{
		FHyperTwistVisionFrameEnvelope Frame;
		Frame.FrameOrdinal = FrameOrdinal;
		Frame.TargetFaceHint = FaceId;
		TrainingSubsystem->SubmitActiveRecognitionFrame(Frame);
	}

	FHyperTwistVisionCommitResult CommitFace(
		UHyperTwistTrainingSubsystem* TrainingSubsystem,
		const FString& FaceId,
		const int32 FrameOrdinal
	)
	{
		SubmitPreviewFrame(TrainingSubsystem, FaceId, FrameOrdinal);

		FHyperTwistVisionCommitRequest Request;
		Request.TargetFace = FaceId;
		return TrainingSubsystem->CommitActiveRecognitionObservation(Request);
	}

	const FHyperTwistVisionLocaleOption* FindLocaleOption(
		const TArray<FHyperTwistVisionLocaleOption>& LocaleOptions,
		const FString& ExpectedLocaleCode
	)
	{
		return LocaleOptions.FindByPredicate(
			[&ExpectedLocaleCode](const FHyperTwistVisionLocaleOption& Candidate)
			{
				return Candidate.LocaleCode == ExpectedLocaleCode;
			}
		);
	}
}

IMPLEMENT_SIMPLE_AUTOMATION_TEST(
	FHyperTwistQbrPhase6RANSessionConfigTest,
	"HyperTwist.Permissive.Qbr.Phase6R.AN.LocalePresentationSessionConfig",
	EAutomationTestFlags::EditorContext | EAutomationTestFlags::EngineFilter
)

bool FHyperTwistQbrPhase6RANSessionConfigTest::RunTest(const FString& Parameters)
{
	UHyperTwistTrainingSubsystem* TrainingSubsystem =
		HyperTwistQbrPhase6RANTestInternal::MakeRecognitionSubsystem(TEXT("phase6r-an-config-session"));
	TestNotNull(TEXT("The recognition subsystem must be constructed for Phase 6R-AN."), TrainingSubsystem);
	if (TrainingSubsystem == nullptr)
	{
		return false;
	}

	FString OpenError;
	TestTrue(TEXT("The recognition session must open for the locale-presentation route."), TrainingSubsystem->OpenActiveRecognitionSession(OpenError));
	TestTrue(TEXT("Opening the recognition session must not report an error."), OpenError.IsEmpty());

	const FHyperTwistTrainingRecognitionSessionState SessionState =
		TrainingSubsystem->GetActiveRecognitionSessionState();

	const FHyperTwistVisionLocaleOption* ArabicLocale =
		HyperTwistQbrPhase6RANTestInternal::FindLocaleOption(
			SessionState.SessionConfig.SolveExplanationProfileDefinition.SupportedLocales,
			TEXT("ar")
		);
	TestNotNull(TEXT("The Arabic locale option must be present."), ArabicLocale);
	if (ArabicLocale != nullptr)
	{
		TestEqual(TEXT("Arabic must remain right-to-left."), ArabicLocale->ScriptDirectionId, TEXT("rtl"));
		TestEqual(TEXT("Arabic must keep the RTL text-flow profile."), ArabicLocale->TextFlowProfileId, TEXT("rtl-word-space-delimited"));
		TestEqual(TEXT("Arabic must use the bounded locale-presentation profile."), ArabicLocale->PresentationProfileId, TEXT("qbr-locale-presentation-v1"));
		TestTrue(TEXT("Arabic must keep complex text shaping enabled."), ArabicLocale->bRequiresComplexTextShaping);
		TestTrue(TEXT("Arabic must keep bundled donor font shipping deferred."), ArabicLocale->bBundledFontAssetDeferred);
	}

	const FHyperTwistVisionLocaleOption* FarsiLocale =
		HyperTwistQbrPhase6RANTestInternal::FindLocaleOption(
			SessionState.SessionConfig.SolveExplanationProfileDefinition.SupportedLocales,
			TEXT("fa")
		);
	TestNotNull(TEXT("The Farsi locale option must be present."), FarsiLocale);
	if (FarsiLocale != nullptr)
	{
		TestEqual(TEXT("Farsi must remain right-to-left."), FarsiLocale->ScriptDirectionId, TEXT("rtl"));
		TestEqual(TEXT("Farsi must keep the RTL text-flow profile."), FarsiLocale->TextFlowProfileId, TEXT("rtl-word-space-delimited"));
		TestTrue(TEXT("Farsi must keep complex text shaping enabled."), FarsiLocale->bRequiresComplexTextShaping);
		TestTrue(TEXT("Farsi must keep bundled donor font shipping deferred."), FarsiLocale->bBundledFontAssetDeferred);
	}

	const FHyperTwistVisionLocaleOption* SimplifiedChineseLocale =
		HyperTwistQbrPhase6RANTestInternal::FindLocaleOption(
			SessionState.SessionConfig.SolveExplanationProfileDefinition.SupportedLocales,
			TEXT("zh")
		);
	TestNotNull(TEXT("The Simplified Chinese locale option must be present."), SimplifiedChineseLocale);
	if (SimplifiedChineseLocale != nullptr)
	{
		TestEqual(TEXT("Simplified Chinese must keep the CJK text-flow profile."), SimplifiedChineseLocale->TextFlowProfileId, TEXT("cjk-character-wrap"));
		TestEqual(TEXT("Simplified Chinese must remain left-to-right in the bounded overlay contract."), SimplifiedChineseLocale->ScriptDirectionId, TEXT("ltr"));
		TestFalse(TEXT("Simplified Chinese must not require complex Arabic-style shaping."), SimplifiedChineseLocale->bRequiresComplexTextShaping);
	}

	return true;
}

IMPLEMENT_SIMPLE_AUTOMATION_TEST(
	FHyperTwistQbrPhase6RANActiveStateTest,
	"HyperTwist.Permissive.Qbr.Phase6R.AN.LocalePresentationActiveState",
	EAutomationTestFlags::EditorContext | EAutomationTestFlags::EngineFilter
)

bool FHyperTwistQbrPhase6RANActiveStateTest::RunTest(const FString& Parameters)
{
	UHyperTwistTrainingSubsystem* TrainingSubsystem =
		HyperTwistQbrPhase6RANTestInternal::MakeRecognitionSubsystem(TEXT("phase6r-an-state-session"));
	TestNotNull(TEXT("The recognition subsystem must be constructed for Phase 6R-AN."), TrainingSubsystem);
	if (TrainingSubsystem == nullptr)
	{
		return false;
	}

	const FHyperTwistVisionCommitResult Result =
		HyperTwistQbrPhase6RANTestInternal::CommitFace(TrainingSubsystem, TEXT("F"), 1);

	TestTrue(TEXT("The webcam shell state must stay structurally valid."), Result.ShellState.IsStructurallyValid());
	TestEqual(TEXT("The default shell locale must remain English."), Result.ShellState.LocaleCode, TEXT("en"));
	TestEqual(TEXT("The active shell locale must remain left-to-right by default."), Result.ShellState.ActiveLocaleScriptDirectionId, TEXT("ltr"));
	TestEqual(TEXT("The active shell locale must keep the word-space text-flow profile by default."), Result.ShellState.ActiveLocaleTextFlowProfileId, TEXT("word-space-delimited"));
	TestEqual(TEXT("The shell must surface the bounded locale-presentation profile id."), Result.ShellState.ActiveLocalePresentationProfileId, TEXT("qbr-locale-presentation-v1"));
	TestFalse(TEXT("The default English shell locale must not require complex text shaping."), Result.ShellState.bActiveLocaleRequiresComplexTextShaping);
	TestTrue(TEXT("The shell must keep bundled donor font shipping deferred."), Result.ShellState.bBundledFontAssetDeferred);

	TestTrue(TEXT("The solve-guidance state must stay structurally valid."), Result.SolveExplanationState.IsStructurallyValid());
	TestEqual(TEXT("The active solve locale must remain English by default."), Result.SolveExplanationState.ActiveLocaleCode, TEXT("en"));
	TestEqual(TEXT("The active solve locale must remain left-to-right by default."), Result.SolveExplanationState.ActiveLocaleScriptDirectionId, TEXT("ltr"));
	TestEqual(TEXT("The active solve locale must keep the word-space text-flow profile by default."), Result.SolveExplanationState.ActiveLocaleTextFlowProfileId, TEXT("word-space-delimited"));
	TestEqual(TEXT("The solve guidance state must surface the bounded locale-presentation profile id."), Result.SolveExplanationState.ActiveLocalePresentationProfileId, TEXT("qbr-locale-presentation-v1"));
	TestFalse(TEXT("The default English solve locale must not require complex text shaping."), Result.SolveExplanationState.bActiveLocaleRequiresComplexTextShaping);
	TestTrue(TEXT("The solve guidance state must keep bundled donor font shipping deferred."), Result.SolveExplanationState.bBundledFontAssetDeferred);

	return true;
}

#endif
