// Copyright HyperTwist, Inc. All Rights Reserved.

#include "Misc/AutomationTest.h"

#include "Engine/GameInstance.h"
#include "HyperTwistBootstrap/HyperTwistContractLibrary.h"
#include "HyperTwistRecognition/HyperTwistSpeechClient.h"
#include "HyperTwistTraining/HyperTwistTrainingSubsystem.h"
#include "UObject/UnrealType.h"

#if WITH_AUTOMATION_TESTS

namespace HyperTwistWhisperCppPhase6RAHTestInternal
{
	FHyperTwistTrainingDeck MakeSpeechDeck()
	{
		FHyperTwistTrainingDeck Deck;
		Deck.DeckId = TEXT("phase6r-ah/native-capture-route-shell");
		Deck.Title = TEXT("Phase 6R-AH Native Capture Route Shell");
		Deck.DeliveryModes = {
			EHyperTwistTrainingDeliveryMode::CoachReviewed
		};

		FHyperTwistTrainingCase TrainingCase;
		TrainingCase.CaseId = TEXT("phase6r-ah-case");
		TrainingCase.PuzzleId = TEXT("cube/3x3x3");
		TrainingCase.PromptKind = EHyperTwistTrainingPromptKind::Sequence;
		TrainingCase.PromptLabel = TEXT("Phase 6R-AH Coach Speech");
		TrainingCase.AllowedDeliveryModes = {
			EHyperTwistTrainingDeliveryMode::CoachReviewed
		};
		Deck.Cases = {TrainingCase};
		return Deck;
	}

	void ForceSpeechClientKind(UHyperTwistTrainingSubsystem* TrainingSubsystem, const FString& ClientKind)
	{
		if (TrainingSubsystem == nullptr)
		{
			return;
		}

		if (FStrProperty* SpeechClientKindProperty = FindFProperty<FStrProperty>(
			UHyperTwistTrainingSubsystem::StaticClass(),
			TEXT("CompanionSpeechClientKind")
		))
		{
			SpeechClientKindProperty->SetPropertyValue_InContainer(TrainingSubsystem, ClientKind);
		}
	}

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

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

		ForceSpeechClientKind(TrainingSubsystem, ClientKind);
		const FHyperTwistTrainingRunState RunState = TrainingSubsystem->StartTrainingRunFromDeck(
			MakeSpeechDeck(),
			TEXT("phase6r-ah-user"),
			SessionId,
			EHyperTwistTrainingDeliveryMode::CoachReviewed
		);
		return RunState.IsStructurallyValid() ? TrainingSubsystem : nullptr;
	}

	FHyperTwistTrainingCompanionSpeechSessionState* ResolveActiveSpeechSessionState(
		UHyperTwistTrainingSubsystem* TrainingSubsystem
	)
	{
		if (TrainingSubsystem == nullptr)
		{
			return nullptr;
		}

		if (FStructProperty* SessionStateProperty = FindFProperty<FStructProperty>(
			UHyperTwistTrainingSubsystem::StaticClass(),
			TEXT("ActiveCompanionSpeechSessionState")
		))
		{
			return SessionStateProperty->ContainerPtrToValuePtr<FHyperTwistTrainingCompanionSpeechSessionState>(
				TrainingSubsystem
			);
		}

		return nullptr;
	}

	void ForcePermissionError(UHyperTwistTrainingSubsystem* TrainingSubsystem, const FString& ErrorText)
	{
		if (FHyperTwistTrainingCompanionSpeechSessionState* SessionState =
				ResolveActiveSpeechSessionState(TrainingSubsystem))
		{
			SessionState->LastError = ErrorText;
			SessionState->ServiceHealth.LastError = ErrorText;
		}
	}

	UHyperTwistHttpSpeechClient* ResolveHttpSpeechClient(UHyperTwistTrainingSubsystem* TrainingSubsystem)
	{
		if (TrainingSubsystem == nullptr)
		{
			return nullptr;
		}

		FString CloseError;
		TrainingSubsystem->CloseActiveCompanionSpeechSession(CloseError);

		if (FObjectPropertyBase* ClientProperty = FindFProperty<FObjectPropertyBase>(
			UHyperTwistTrainingSubsystem::StaticClass(),
			TEXT("ActiveCompanionSpeechClientObject")
		))
		{
			return Cast<UHyperTwistHttpSpeechClient>(
				ClientProperty->GetObjectPropertyValue_InContainer(TrainingSubsystem)
			);
		}

		return nullptr;
	}

	void ForcePreparationState(
		UHyperTwistTrainingSubsystem* TrainingSubsystem,
		const FString& SessionId
	)
	{
		if (FHyperTwistTrainingCompanionSpeechSessionState* SessionState =
				ResolveActiveSpeechSessionState(TrainingSubsystem))
		{
			SessionState->bSessionOpen = true;
			SessionState->ActiveSessionId = SessionId;
			SessionState->OpenedAtUtc = FDateTime::UtcNow().ToIso8601();
			SessionState->LastUpdatedAtUtc = SessionState->OpenedAtUtc;
			SessionState->SessionConfig = UHyperTwistContractLibrary::MakeSampleSpeechSessionConfig();
			SessionState->SessionConfig.SessionId = SessionId;
			SessionState->LastError = TEXT("service-base-url-missing");
		}
	}

	void ForceRetryState(
		UHyperTwistTrainingSubsystem* TrainingSubsystem,
		const FString& SessionId,
		const FString& ErrorText
	)
	{
		if (FHyperTwistTrainingCompanionSpeechSessionState* SessionState =
				ResolveActiveSpeechSessionState(TrainingSubsystem))
		{
			SessionState->bSessionOpen = true;
			SessionState->ActiveSessionId = SessionId;
			SessionState->OpenedAtUtc = FDateTime::UtcNow().ToIso8601();
			SessionState->LastUpdatedAtUtc = SessionState->OpenedAtUtc;
			SessionState->SessionConfig = UHyperTwistContractLibrary::MakeSampleSpeechSessionConfig();
			SessionState->SessionConfig.SessionId = SessionId;
			SessionState->LastError = ErrorText;
			SessionState->ServiceHealth.LastError = ErrorText;
			SessionState->ServiceHealth.bReady = false;
		}
	}

	bool ContainsPanelId(
		const TArray<FHyperTwistSpeechShellPanelLayout>& Panels,
		const FString& ExpectedPanelId
	)
	{
		for (const FHyperTwistSpeechShellPanelLayout& Panel : Panels)
		{
			if (Panel.PanelId == ExpectedPanelId)
			{
				return true;
			}
		}

		return false;
	}

	bool ContainsActionId(
		const TArray<FHyperTwistSpeechShellActionBinding>& ActionBindings,
		const FString& ExpectedActionId
	)
	{
		for (const FHyperTwistSpeechShellActionBinding& ActionBinding : ActionBindings)
		{
			if (ActionBinding.ActionId == ExpectedActionId)
			{
				return true;
			}
		}

		return false;
	}
}

IMPLEMENT_SIMPLE_AUTOMATION_TEST(
	FHyperTwistWhisperCppPhase6RAHNativeCaptureRouteShellSessionConfigTest,
	"HyperTwist.Permissive.WhisperCpp.Phase6R.AH.NativeCaptureRouteShellSessionConfig",
	EAutomationTestFlags::EditorContext | EAutomationTestFlags::EngineFilter
)

bool FHyperTwistWhisperCppPhase6RAHNativeCaptureRouteShellSessionConfigTest::RunTest(
	const FString& Parameters
)
{
	UHyperTwistTrainingSubsystem* TrainingSubsystem =
		HyperTwistWhisperCppPhase6RAHTestInternal::MakeSpeechSubsystem(
			TEXT("phase6r-ah-config-session"),
			TEXT("mock")
		);
	TestNotNull(TEXT("The speech subsystem must be constructed for Phase 6R-AH."), TrainingSubsystem);
	if (TrainingSubsystem == nullptr)
	{
		return false;
	}

	FString OpenError;
	TestTrue(TEXT("The native capture-route shell route must open a speech session."), TrainingSubsystem->OpenActiveCompanionSpeechSession(OpenError));
	TestTrue(TEXT("Opening the speech session must not report an error."), OpenError.IsEmpty());

	const FHyperTwistSpeechSessionConfig& Config =
		TrainingSubsystem->GetActiveCompanionSpeechSessionState().SessionConfig;

	TestTrue(TEXT("The shell session config must remain structurally valid."), Config.IsStructurallyValid());
	TestEqual(TEXT("The shell profile id must be present."), Config.NativeCaptureRouteShellProfileId, TEXT("speech-native-capture-route-shell-v1"));
	TestTrue(TEXT("The shell profile must remain structurally valid."), Config.NativeCaptureRouteShellProfileDefinition.IsStructurallyValid());
	TestEqual(TEXT("The shell must preserve the operator-facing shell kind."), Config.NativeCaptureRouteShellProfileDefinition.ShellKind, TEXT("operator-native-capture-route-workflow"));
	TestEqual(TEXT("The shell must preserve the route inspect action id."), Config.NativeCaptureRouteShellProfileDefinition.RouteInspectActionId, TEXT("inspect-native-capture-route"));
	TestEqual(TEXT("The shell must preserve the retry action id."), Config.NativeCaptureRouteShellProfileDefinition.PreparationRetryActionId, TEXT("retry-capture-route"));
	TestEqual(TEXT("The shell must preserve the reopen action id."), Config.NativeCaptureRouteShellProfileDefinition.SessionReopenActionId, TEXT("reopen-speech-session"));
	TestTrue(TEXT("The shell must include the ownership summary panel."), HyperTwistWhisperCppPhase6RAHTestInternal::ContainsPanelId(Config.NativeCaptureRouteShellProfileDefinition.Panels, TEXT("capture-route-ownership-summary-card")));
	TestTrue(TEXT("The shell must include the route inspect action binding."), HyperTwistWhisperCppPhase6RAHTestInternal::ContainsActionId(Config.NativeCaptureRouteShellProfileDefinition.ActionBindings, TEXT("inspect-native-capture-route")));
	return true;
}

IMPLEMENT_SIMPLE_AUTOMATION_TEST(
	FHyperTwistWhisperCppPhase6RAHNativeCaptureRouteShellClearedStateTest,
	"HyperTwist.Permissive.WhisperCpp.Phase6R.AH.NativeCaptureRouteShellClearedState",
	EAutomationTestFlags::EditorContext | EAutomationTestFlags::EngineFilter
)

bool FHyperTwistWhisperCppPhase6RAHNativeCaptureRouteShellClearedStateTest::RunTest(
	const FString& Parameters
)
{
	UHyperTwistTrainingSubsystem* TrainingSubsystem =
		HyperTwistWhisperCppPhase6RAHTestInternal::MakeSpeechSubsystem(
			TEXT("phase6r-ah-cleared-session"),
			TEXT("mock")
		);
	TestNotNull(TEXT("The speech subsystem must be constructed for Phase 6R-AH."), TrainingSubsystem);
	if (TrainingSubsystem == nullptr)
	{
		return false;
	}

	FString OpenError;
	TestTrue(TEXT("The native capture-route shell route must open a speech session."), TrainingSubsystem->OpenActiveCompanionSpeechSession(OpenError));
	TestTrue(TEXT("Opening the speech session must not report an error."), OpenError.IsEmpty());

	const FHyperTwistTrainingCompanionSpeechSessionState SessionState =
		TrainingSubsystem->GetActiveCompanionSpeechSessionState();
	const FHyperTwistSpeechServiceHealth& Health = SessionState.ServiceHealth;
	const FHyperTwistSpeechNativeCaptureRouteShellState& ShellState =
		SessionState.NativeCaptureRouteShellState;

	TestTrue(TEXT("The speech service health must expose the native capture-route shell."), Health.Capabilities.Contains(TEXT("nativeCaptureRouteWorkflowShell")));
	TestTrue(TEXT("The speech service health must expose the ownership summary card capability."), Health.Capabilities.Contains(TEXT("captureRouteOwnershipSummaryCard")));
	TestTrue(TEXT("The speech service health must expose the preparation card capability."), Health.Capabilities.Contains(TEXT("captureRoutePreparationCard")));
	TestTrue(TEXT("The speech service health must expose the session reopen card capability."), Health.Capabilities.Contains(TEXT("captureRouteSessionReopenCard")));

	TestTrue(TEXT("The cleared native capture-route shell state must remain structurally valid."), ShellState.IsStructurallyValid());
	TestEqual(TEXT("The shell must preserve the mock provider profile."), ShellState.ActiveProviderProfileId, TEXT("speech-provider/mock-offline-profile-v1"));
	TestEqual(TEXT("The shell must preserve the ready route state."), ShellState.CaptureRouteStateId, TEXT("route-ready"));
	TestTrue(TEXT("The shell must keep the ownership summary visible."), ShellState.bOwnershipSummaryVisible);
	TestFalse(TEXT("The shell must not surface the preparation card on a healthy route."), ShellState.bPreparationCardVisible);
	TestFalse(TEXT("The shell must not surface the session reopen card on a healthy route."), ShellState.bSessionReopenCardVisible);
	TestFalse(TEXT("The shell must not surface the permission dependency banner on a healthy route."), ShellState.bPermissionDependencyBannerVisible);
	TestEqual(TEXT("The shell must preserve zero active issues on a healthy route."), ShellState.ActiveIssueCount, 0);
	TestTrue(TEXT("The shell must preserve the route inspect action."), ShellState.AvailableActionIds.Contains(TEXT("inspect-native-capture-route")));
	TestTrue(TEXT("The shell must preserve the retry action."), ShellState.AvailableActionIds.Contains(TEXT("retry-capture-route")));
	return true;
}

IMPLEMENT_SIMPLE_AUTOMATION_TEST(
	FHyperTwistWhisperCppPhase6RAHNativeCaptureRouteShellPermissionDependencyTest,
	"HyperTwist.Permissive.WhisperCpp.Phase6R.AH.NativeCaptureRouteShellPermissionDependency",
	EAutomationTestFlags::EditorContext | EAutomationTestFlags::EngineFilter
)

bool FHyperTwistWhisperCppPhase6RAHNativeCaptureRouteShellPermissionDependencyTest::RunTest(
	const FString& Parameters
)
{
	UHyperTwistTrainingSubsystem* TrainingSubsystem =
		HyperTwistWhisperCppPhase6RAHTestInternal::MakeSpeechSubsystem(
			TEXT("phase6r-ah-permission-session"),
			TEXT("mock")
		);
	TestNotNull(TEXT("The speech subsystem must be constructed for Phase 6R-AH."), TrainingSubsystem);
	if (TrainingSubsystem == nullptr)
	{
		return false;
	}

	FString OpenError;
	TestTrue(TEXT("The native capture-route shell route must open a speech session."), TrainingSubsystem->OpenActiveCompanionSpeechSession(OpenError));
	TestTrue(TEXT("Opening the speech session must not report an error."), OpenError.IsEmpty());

	HyperTwistWhisperCppPhase6RAHTestInternal::ForcePermissionError(
		TrainingSubsystem,
		TEXT("microphone-permission-required")
	);
	TrainingSubsystem->RefreshCompanionSpeechServiceHealthForAutomation();

	const FHyperTwistSpeechNativeCaptureRouteShellState& ShellState =
		TrainingSubsystem->GetActiveCompanionSpeechSessionState().NativeCaptureRouteShellState;

	TestTrue(TEXT("The permission-dependent native capture-route shell state must remain structurally valid."), ShellState.IsStructurallyValid());
	TestEqual(TEXT("The shell must preserve the waiting workflow state id."), ShellState.WorkflowStateId, TEXT("capture-route-awaiting-permission"));
	TestEqual(TEXT("The shell must preserve the waiting capture-route posture."), ShellState.CaptureRouteStateId, TEXT("route-waiting-for-permission"));
	TestTrue(TEXT("The shell must surface the permission dependency banner."), ShellState.bPermissionDependencyBannerVisible);
	TestTrue(TEXT("The shell must clear workflow-ready posture."), !ShellState.bWorkflowReady);
	TestEqual(TEXT("The shell must classify the active issue correctly."), ShellState.ActiveIssue.IssueKind, TEXT("permission-workflow-dependency"));
	TestTrue(TEXT("The shell must preserve the bounded permission workflow action."), ShellState.AvailableActionIds.Contains(TEXT("resolve-device-permission-workflow")));
	return true;
}

IMPLEMENT_SIMPLE_AUTOMATION_TEST(
	FHyperTwistWhisperCppPhase6RAHNativeCaptureRouteShellPreparationStateTest,
	"HyperTwist.Permissive.WhisperCpp.Phase6R.AH.NativeCaptureRouteShellPreparationState",
	EAutomationTestFlags::EditorContext | EAutomationTestFlags::EngineFilter
)

bool FHyperTwistWhisperCppPhase6RAHNativeCaptureRouteShellPreparationStateTest::RunTest(
	const FString& Parameters
)
{
	UHyperTwistTrainingSubsystem* TrainingSubsystem =
		HyperTwistWhisperCppPhase6RAHTestInternal::MakeSpeechSubsystem(
			TEXT("phase6r-ah-preparation-session"),
			TEXT("http-sidecar")
		);
	TestNotNull(TEXT("The speech subsystem must be constructed for Phase 6R-AH."), TrainingSubsystem);
	if (TrainingSubsystem == nullptr)
	{
		return false;
	}

	UHyperTwistHttpSpeechClient* HttpSpeechClient =
		HyperTwistWhisperCppPhase6RAHTestInternal::ResolveHttpSpeechClient(TrainingSubsystem);
	TestNotNull(TEXT("The provider-backed speech client must be available for the preparation shell test."), HttpSpeechClient);
	if (HttpSpeechClient == nullptr)
	{
		return false;
	}

	HttpSpeechClient->ServiceBaseUrl.Reset();
	HyperTwistWhisperCppPhase6RAHTestInternal::ForcePreparationState(
		TrainingSubsystem,
		TEXT("phase6r-ah-preparation-session")
	);
	TrainingSubsystem->RefreshCompanionSpeechServiceHealthForAutomation();

	const FHyperTwistSpeechNativeCaptureRouteShellState& ShellState =
		TrainingSubsystem->GetActiveCompanionSpeechSessionState().NativeCaptureRouteShellState;

	TestTrue(TEXT("The preparation-required native capture-route shell state must remain structurally valid."), ShellState.IsStructurallyValid());
	TestEqual(TEXT("The shell must preserve the preparation workflow state id."), ShellState.WorkflowStateId, TEXT("capture-route-preparation-required"));
	TestEqual(TEXT("The shell must preserve the awaiting-endpoint route posture."), ShellState.CaptureRouteStateId, TEXT("route-awaiting-endpoint"));
	TestTrue(TEXT("The shell must surface the preparation card."), ShellState.bPreparationCardVisible);
	TestTrue(TEXT("The shell must surface route inspection."), ShellState.bRouteInspectVisible);
	TestEqual(TEXT("The shell must classify the active issue correctly."), ShellState.ActiveIssue.IssueKind, TEXT("capture-route-preparation-required"));
	TestEqual(TEXT("The shell must carry the missing-endpoint route error."), ShellState.LastRouteError, TEXT("service-base-url-missing"));
	return true;
}

IMPLEMENT_SIMPLE_AUTOMATION_TEST(
	FHyperTwistWhisperCppPhase6RAHNativeCaptureRouteShellRetryStateTest,
	"HyperTwist.Permissive.WhisperCpp.Phase6R.AH.NativeCaptureRouteShellRetryState",
	EAutomationTestFlags::EditorContext | EAutomationTestFlags::EngineFilter
)

bool FHyperTwistWhisperCppPhase6RAHNativeCaptureRouteShellRetryStateTest::RunTest(
	const FString& Parameters
)
{
	UHyperTwistTrainingSubsystem* TrainingSubsystem =
		HyperTwistWhisperCppPhase6RAHTestInternal::MakeSpeechSubsystem(
			TEXT("phase6r-ah-retry-session"),
			TEXT("http-sidecar")
		);
	TestNotNull(TEXT("The speech subsystem must be constructed for the retry shell test."), TrainingSubsystem);
	if (TrainingSubsystem == nullptr)
	{
		return false;
	}

	UHyperTwistHttpSpeechClient* HttpSpeechClient =
		HyperTwistWhisperCppPhase6RAHTestInternal::ResolveHttpSpeechClient(TrainingSubsystem);
	TestNotNull(TEXT("The provider-backed speech client must be available for the retry shell test."), HttpSpeechClient);
	if (HttpSpeechClient == nullptr)
	{
		return false;
	}

	HttpSpeechClient->RequestTimeoutSeconds = 0.25f;
	HyperTwistWhisperCppPhase6RAHTestInternal::ForceRetryState(
		TrainingSubsystem,
		TEXT("phase6r-ah-retry-session"),
		TEXT("request-failed")
	);
	TrainingSubsystem->RefreshCompanionSpeechServiceHealthForAutomation();

	const FHyperTwistSpeechNativeCaptureRouteShellState& ShellState =
		TrainingSubsystem->GetActiveCompanionSpeechSessionState().NativeCaptureRouteShellState;

	TestTrue(TEXT("The retry-required native capture-route shell state must remain structurally valid."), ShellState.IsStructurallyValid());
	TestEqual(TEXT("The shell must preserve the retry workflow state id."), ShellState.WorkflowStateId, TEXT("capture-route-retry-required"));
	TestEqual(TEXT("The shell must preserve the retry capture-route posture."), ShellState.CaptureRouteStateId, TEXT("route-retry-required"));
	TestTrue(TEXT("The shell must surface the preparation card for route retry."), ShellState.bPreparationCardVisible);
	TestTrue(TEXT("The shell must surface the retry action."), ShellState.bPreparationRetryVisible);
	TestEqual(TEXT("The shell must classify the active issue correctly."), ShellState.ActiveIssue.IssueKind, TEXT("capture-route-retry-required"));
	TestTrue(TEXT("The shell must preserve the bounded retry action."), ShellState.AvailableActionIds.Contains(TEXT("retry-capture-route")));
	TestEqual(TEXT("The shell must preserve the provider-backed transport failure."), ShellState.LastRouteError, TEXT("request-failed"));
	return true;
}

#endif
