// Copyright HyperTwist, Inc. All Rights Reserved.

#include "Misc/AutomationTest.h"

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

#if WITH_AUTOMATION_TESTS

namespace HyperTwistWhisperCppPhase6RACTestInternal
{
	FHyperTwistTrainingDeck MakeSpeechDeck()
	{
		FHyperTwistTrainingDeck Deck;
		Deck.DeckId = TEXT("phase6r-ac/provider-receipt-review");
		Deck.Title = TEXT("Phase 6R-AC Provider Receipt Review");
		Deck.DeliveryModes = {
			EHyperTwistTrainingDeliveryMode::CoachReviewed
		};

		FHyperTwistTrainingCase TrainingCase;
		TrainingCase.CaseId = TEXT("phase6r-ac-case");
		TrainingCase.PuzzleId = TEXT("cube/3x3x3");
		TrainingCase.PromptKind = EHyperTwistTrainingPromptKind::Sequence;
		TrainingCase.PromptLabel = TEXT("Phase 6R-AC 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-ac-user"),
			SessionId,
			EHyperTwistTrainingDeliveryMode::CoachReviewed
		);
		return RunState.IsStructurallyValid() ? TrainingSubsystem : nullptr;
	}

	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;
	}

	FHyperTwistSpeechUtteranceEnvelope MakeUtterance()
	{
		FHyperTwistSpeechUtteranceEnvelope Utterance;
		Utterance.AudioRef = TEXT("ready-coach");
		Utterance.SpeechStartMs = 120;
		Utterance.SpeechEndMs = 840;
		Utterance.SilenceGapMs = 240;
		return Utterance;
	}

	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(
	FHyperTwistWhisperCppPhase6RACProviderReceiptReviewSessionConfigTest,
	"HyperTwist.Permissive.WhisperCpp.Phase6R.AC.ProviderReceiptReviewSessionConfig",
	EAutomationTestFlags::EditorContext | EAutomationTestFlags::EngineFilter
)

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

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

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

	TestTrue(TEXT("The receipt-review session config must remain structurally valid."), Config.IsStructurallyValid());
	TestEqual(TEXT("The receipt-review shell profile id must be present."), Config.ProviderReceiptReviewShellProfileId, TEXT("speech-provider-receipt-review-shell-v1"));
	TestTrue(TEXT("The receipt-review shell profile must remain structurally valid."), Config.ProviderReceiptReviewShellProfileDefinition.IsStructurallyValid());
	TestEqual(TEXT("The receipt-review shell must preserve the operator-facing shell kind."), Config.ProviderReceiptReviewShellProfileDefinition.ShellKind, TEXT("operator-provider-receipt-review"));
	TestEqual(TEXT("The receipt-review shell must preserve the posted-charge inspect action id."), Config.ProviderReceiptReviewShellProfileDefinition.PostedChargeInspectActionId, TEXT("inspect-provider-posted-charges"));
	TestEqual(TEXT("The receipt-review shell must preserve the variance review action id."), Config.ProviderReceiptReviewShellProfileDefinition.VarianceReviewActionId, TEXT("review-provider-charge-variance"));
	TestTrue(TEXT("The receipt-review shell must include the receipt timeline panel."), HyperTwistWhisperCppPhase6RACTestInternal::ContainsPanelId(Config.ProviderReceiptReviewShellProfileDefinition.Panels, TEXT("receipt-timeline-card")));
	TestTrue(TEXT("The receipt-review shell must include the posted-charge inspection action."), HyperTwistWhisperCppPhase6RACTestInternal::ContainsActionId(Config.ProviderReceiptReviewShellProfileDefinition.ActionBindings, TEXT("inspect-provider-posted-charges")));
	return true;
}

IMPLEMENT_SIMPLE_AUTOMATION_TEST(
	FHyperTwistWhisperCppPhase6RACProviderReceiptReviewShellStateTest,
	"HyperTwist.Permissive.WhisperCpp.Phase6R.AC.ProviderReceiptReviewShellState",
	EAutomationTestFlags::EditorContext | EAutomationTestFlags::EngineFilter
)

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

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

	const FHyperTwistSpeechTranscriptResult Result =
		TrainingSubsystem->SubmitActiveCompanionSpeechUtterance(
			HyperTwistWhisperCppPhase6RACTestInternal::MakeUtterance()
		);
	TestTrue(TEXT("The mock receipt-review utterance must produce a final transcript."), Result.bIsFinal);
	TestTrue(TEXT("The mock receipt-review utterance must remain structurally valid."), Result.IsStructurallyValid());

	const FHyperTwistTrainingCompanionSpeechSessionState SessionState =
		TrainingSubsystem->GetActiveCompanionSpeechSessionState();
	const FHyperTwistSpeechServiceHealth& Health = SessionState.ServiceHealth;
	const FHyperTwistSpeechProviderReceiptReviewShellState& ReceiptReview =
		SessionState.ProviderReceiptReviewShellState;

	TestTrue(TEXT("The service health must expose the receipt-review shell."), Health.Capabilities.Contains(TEXT("providerReceiptReviewShell")));
	TestTrue(TEXT("The service health must expose posted-charge inspection."), Health.Capabilities.Contains(TEXT("providerPostedChargeInspection")));
	TestTrue(TEXT("The service health must expose charge-variance review."), Health.Capabilities.Contains(TEXT("providerChargeVarianceReview")));

	TestTrue(TEXT("The receipt-review shell state must remain structurally valid."), ReceiptReview.IsStructurallyValid());
	TestEqual(TEXT("The receipt-review shell must preserve the mock provider profile."), ReceiptReview.ActiveProviderProfileId, TEXT("speech-provider/mock-offline-profile-v1"));
	TestEqual(TEXT("The receipt-review shell must retain exactly two bounded receipt entries after open and submit."), ReceiptReview.ReceiptEntryCount, 2);
	TestEqual(TEXT("The receipt-review shell must preserve the latest source kind."), ReceiptReview.LatestSourceKind, TEXT("history-derived-estimate-only"));
	TestTrue(TEXT("The receipt-review shell must preserve summary readiness."), ReceiptReview.bReceiptSummaryReady);
	TestTrue(TEXT("The receipt-review shell must preserve posted-charge inspection readiness."), ReceiptReview.bPostedChargeInspectionReady);
	TestTrue(TEXT("The receipt-review shell must preserve variance-review readiness."), ReceiptReview.bVarianceReviewReady);
	TestTrue(TEXT("The receipt-review shell must preserve the posted-charge inspection action."), ReceiptReview.AvailableActionIds.Contains(TEXT("inspect-provider-posted-charges")));
	TestTrue(TEXT("The receipt-review shell must preserve the variance-review action."), ReceiptReview.AvailableActionIds.Contains(TEXT("review-provider-charge-variance")));
	TestEqual(TEXT("The receipt-review shell must preserve zero provider-posted charges in the mock route."), ReceiptReview.ProviderPostedChargeCount, 0);
	TestEqual(TEXT("The receipt-review shell must preserve the estimate-only entry count."), ReceiptReview.EstimateOnlyEntryCount, 2);
	TestTrue(TEXT("The receipt-review shell must accumulate the mock estimated cost."), FMath::IsNearlyEqual(ReceiptReview.TotalEstimatedCostUsd, 0.02f));
	TestTrue(TEXT("The receipt-review shell must preserve zero variance while no provider charge is posted."), FMath::IsNearlyEqual(ReceiptReview.TotalAbsoluteVarianceUsd, 0.0f));
	TestEqual(TEXT("The receipt-review shell must surface the pending provider-charge issue."), ReceiptReview.ActiveIssue.IssueKind, TEXT("provider-charge-pending"));
	TestTrue(TEXT("The receipt-review summary text must preserve the bounded posted-charge count."), ReceiptReview.ReceiptSummaryText.Contains(TEXT("providerPostedChargeCount=0")));
	return true;
}

IMPLEMENT_SIMPLE_AUTOMATION_TEST(
	FHyperTwistWhisperCppPhase6RACProviderBackedReceiptReviewFallbackTest,
	"HyperTwist.Permissive.WhisperCpp.Phase6R.AC.ProviderBackedReceiptReviewFallback",
	EAutomationTestFlags::EditorContext | EAutomationTestFlags::EngineFilter
)

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

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

	HttpSpeechClient->ServiceBaseUrl.Reset();

	FString OpenError;
	TestFalse(TEXT("The provider-backed receipt-review path must fail cleanly when no provider endpoint is configured."), TrainingSubsystem->OpenActiveCompanionSpeechSession(OpenError));
	TestEqual(TEXT("The provider-backed receipt-review path must report the missing service base URL."), OpenError, TEXT("service-base-url-missing"));

	const FHyperTwistTrainingCompanionSpeechSessionState SessionState =
		TrainingSubsystem->GetActiveCompanionSpeechSessionState();
	const FHyperTwistSpeechProviderReceiptReviewShellState& ReceiptReview =
		SessionState.ProviderReceiptReviewShellState;

	TestTrue(TEXT("The provider-backed receipt-review fallback must remain structurally valid."), ReceiptReview.IsStructurallyValid());
	TestEqual(TEXT("The fallback receipt-review shell must preserve the sidecar profile id."), ReceiptReview.ActiveProviderProfileId, TEXT("speech-provider/local-http-sidecar-profile-v1"));
	TestEqual(TEXT("The fallback receipt-review shell must preserve the fallback source kind."), ReceiptReview.LatestSourceKind, TEXT("provider-fallback-health"));
	TestEqual(TEXT("The fallback receipt-review shell must preserve one receipt entry."), ReceiptReview.ReceiptEntryCount, 1);
	TestEqual(TEXT("The fallback receipt-review shell must surface one active issue."), ReceiptReview.ActiveIssueCount, 1);
	TestEqual(TEXT("The fallback receipt-review shell must surface the route-degraded issue kind."), ReceiptReview.ActiveIssue.IssueKind, TEXT("route-degraded"));
	TestTrue(TEXT("The fallback receipt-review shell must still expose summary readiness for bounded inspection output."), ReceiptReview.bReceiptSummaryReady);
	TestTrue(TEXT("The fallback receipt-review summary text must preserve the missing-endpoint reason."), ReceiptReview.ReceiptSummaryText.Contains(TEXT("service-base-url-missing")));
	return true;
}

#endif
