// 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 HyperTwistRubixCubeSolverPhase6RQTestInternal
{
	FHyperTwistTrainingDeck MakeRecognitionDeck()
	{
		FHyperTwistTrainingDeck Deck;
		Deck.DeckId = TEXT("phase6r-q/rubix-cube-solver-solve-explanation");
		Deck.Title = TEXT("Phase 6R-Q Rubix Cube Solver Solve Explanation");
		Deck.DeliveryModes = {
			EHyperTwistTrainingDeliveryMode::RecognitionAssisted,
			EHyperTwistTrainingDeliveryMode::CoachReviewed
		};

		FHyperTwistTrainingCase TrainingCase;
		TrainingCase.CaseId = TEXT("phase6r-q-case");
		TrainingCase.PuzzleId = TEXT("cube/3x3x3");
		TrainingCase.PromptKind = EHyperTwistTrainingPromptKind::Recognition;
		TrainingCase.PromptLabel = TEXT("Phase 6R-Q 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-q-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);
	}
}

IMPLEMENT_SIMPLE_AUTOMATION_TEST(
	FHyperTwistRubixCubeSolverPhase6RQSolveExplanationSessionConfigTest,
	"HyperTwist.Permissive.RubixCubeSolver.Phase6R.Q.SolveExplanationSessionConfig",
	EAutomationTestFlags::EditorContext | EAutomationTestFlags::EngineFilter
)

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

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

	const FHyperTwistTrainingRecognitionSessionState SessionState =
		TrainingSubsystem->GetActiveRecognitionSessionState();
	TestEqual(
		TEXT("The solve-explanation route must normalize the first-party explanation profile id."),
		SessionState.SessionConfig.SolveExplanationProfileId,
		TEXT("classic-cube-solve-explanation-v1")
	);
	TestTrue(
		TEXT("The solve-explanation route must provide a structurally valid explanation profile definition."),
		SessionState.SessionConfig.SolveExplanationProfileDefinition.IsStructurallyValid()
	);
	TestEqual(
		TEXT("The solve-explanation route must retain eight bounded solve stages."),
		SessionState.SessionConfig.SolveExplanationProfileDefinition.Steps.Num(),
		8
	);
	TestEqual(
		TEXT("The solve-explanation route must retain four bounded explanation actions."),
		SessionState.SessionConfig.SolveExplanationProfileDefinition.ActionBindings.Num(),
		4
	);
	TestFalse(
		TEXT("The solve-explanation route must still defer playback-stage ownership in this packet."),
		SessionState.SessionConfig.SolveExplanationProfileDefinition.bSupportsPlaybackStage
	);
	return true;
}

IMPLEMENT_SIMPLE_AUTOMATION_TEST(
	FHyperTwistRubixCubeSolverPhase6RQSolveExplanationPartialStateTest,
	"HyperTwist.Permissive.RubixCubeSolver.Phase6R.Q.SolveExplanationPartialState",
	EAutomationTestFlags::EditorContext | EAutomationTestFlags::EngineFilter
)

bool FHyperTwistRubixCubeSolverPhase6RQSolveExplanationPartialStateTest::RunTest(const FString& Parameters)
{
	UHyperTwistTrainingSubsystem* TrainingSubsystem =
		HyperTwistRubixCubeSolverPhase6RQTestInternal::MakeRecognitionSubsystem(TEXT("phase6r-q-partial-session"));
	TestNotNull(TEXT("The recognition subsystem must be constructed for Phase 6R-Q."), TrainingSubsystem);
	if (TrainingSubsystem == nullptr)
	{
		return false;
	}

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

	TestTrue(TEXT("The partial commit route must carry a structurally valid solve explanation state."), Result.SolveExplanationState.IsStructurallyValid());
	TestFalse(TEXT("Solve guidance must stay locked before a full reconstruction is available."), Result.SolveExplanationState.bReadyForExplanation);
	TestFalse(TEXT("The solve explanation start action must stay hidden before capture completes."), Result.SolveExplanationState.bStartExplanationVisible);
	TestEqual(TEXT("The partial solve route must direct the user back to capture."), Result.SolveExplanationState.RecommendedStageId, TEXT("capture-remaining-faces"));
	TestTrue(TEXT("The partial solve route must keep the full reconstruction guard explicit."), Result.SolveExplanationState.bRequiresFullReconstruction);
	TestEqual(TEXT("The partial solve route must still expose the full bounded step count."), Result.SolveExplanationState.TotalStepCount, 8);
	return true;
}

IMPLEMENT_SIMPLE_AUTOMATION_TEST(
	FHyperTwistRubixCubeSolverPhase6RQSolveExplanationCompleteStateTest,
	"HyperTwist.Permissive.RubixCubeSolver.Phase6R.Q.SolveExplanationCompleteState",
	EAutomationTestFlags::EditorContext | EAutomationTestFlags::EngineFilter
)

bool FHyperTwistRubixCubeSolverPhase6RQSolveExplanationCompleteStateTest::RunTest(const FString& Parameters)
{
	UHyperTwistTrainingSubsystem* TrainingSubsystem =
		HyperTwistRubixCubeSolverPhase6RQTestInternal::MakeRecognitionSubsystem(TEXT("phase6r-q-complete-session"));
	TestNotNull(TEXT("The recognition subsystem must be constructed for Phase 6R-Q."), TrainingSubsystem);
	if (TrainingSubsystem == nullptr)
	{
		return false;
	}

	const TArray<FString> FaceOrder = {
		TEXT("U"),
		TEXT("R"),
		TEXT("F"),
		TEXT("D"),
		TEXT("L"),
		TEXT("B")
	};

	FHyperTwistVisionCommitResult Result;
	for (int32 FaceOrdinal = 0; FaceOrdinal < FaceOrder.Num(); ++FaceOrdinal)
	{
		Result = HyperTwistRubixCubeSolverPhase6RQTestInternal::CommitFace(
			TrainingSubsystem,
			FaceOrder[FaceOrdinal],
			FaceOrdinal + 1
		);
	}

	TestTrue(TEXT("The completed solve route must carry a structurally valid reconstruction session."), Result.ReconstructionSession.IsStructurallyValid());
	TestTrue(TEXT("The completed solve route must carry a structurally valid solve explanation state."), Result.SolveExplanationState.IsStructurallyValid());
	TestTrue(TEXT("The completed solve route must carry a full classic cube net."), Result.ReconstructionSession.bHasCompleteClassicCubeNet);
	TestTrue(TEXT("Solve guidance must unlock after the full reconstruction completes."), Result.SolveExplanationState.bReadyForExplanation);
	TestTrue(TEXT("The solve explanation start action must be visible after reconstruction completes."), Result.SolveExplanationState.bStartExplanationVisible);
	TestFalse(TEXT("The solve explanation route must not expose next-step navigation before explanation starts."), Result.SolveExplanationState.bNextStepVisible);
	TestFalse(TEXT("The solve explanation route must not expose previous-step navigation before explanation starts."), Result.SolveExplanationState.bPreviousStepVisible);
	TestTrue(TEXT("The solve explanation route must keep playback deferred in this packet."), Result.SolveExplanationState.bPlaybackDeferred);
	TestEqual(TEXT("The solve explanation route must recommend the orientation stage first."), Result.SolveExplanationState.RecommendedStageId, TEXT("orient-centers"));
	TestEqual(TEXT("The solve explanation route must keep the bounded eight-stage ladder."), Result.SolveExplanationState.TotalStepCount, 8);
	TestEqual(TEXT("The browser shell must remain in cube-edit after reconstruction completes."), Result.BrowserShellState.ActiveStageId, TEXT("cube-edit"));
	return true;
}

#endif
