// 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 HyperTwistWhisperCppPhase6RABTestInternal
{
	FHyperTwistTrainingDeck MakeSpeechDeck()
	{
		FHyperTwistTrainingDeck Deck;
		Deck.DeckId = TEXT("phase6r-ab/provider-usage-cost-history-export");
		Deck.Title = TEXT("Phase 6R-AB Provider Usage/Cost History Export");
		Deck.DeliveryModes = {
			EHyperTwistTrainingDeliveryMode::CoachReviewed
		};

		FHyperTwistTrainingCase TrainingCase;
		TrainingCase.CaseId = TEXT("phase6r-ab-case");
		TrainingCase.PuzzleId = TEXT("cube/3x3x3");
		TrainingCase.PromptKind = EHyperTwistTrainingPromptKind::Sequence;
		TrainingCase.PromptLabel = TEXT("Phase 6R-AB 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-ab-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(
	FHyperTwistWhisperCppPhase6RABUsageCostHistoryExportSessionConfigTest,
	"HyperTwist.Permissive.WhisperCpp.Phase6R.AB.UsageCostHistoryExportSessionConfig",
	EAutomationTestFlags::EditorContext | EAutomationTestFlags::EngineFilter
)

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

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

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

	TestTrue(TEXT("The history/export session config must remain structurally valid."), Config.IsStructurallyValid());
	TestEqual(TEXT("The history/export shell profile id must be present."), Config.UsageCostHistoryExportShellProfileId, TEXT("speech-provider-usage-cost-history-export-shell-v1"));
	TestTrue(TEXT("The history/export shell profile must remain structurally valid."), Config.UsageCostHistoryExportShellProfileDefinition.IsStructurallyValid());
	TestEqual(TEXT("The history/export shell must preserve the operator-facing shell kind."), Config.UsageCostHistoryExportShellProfileDefinition.ShellKind, TEXT("operator-usage-cost-history-export"));
	TestEqual(TEXT("The history/export shell must preserve the export preview action id."), Config.UsageCostHistoryExportShellProfileDefinition.ExportPreviewActionId, TEXT("preview-provider-usage-cost-export"));
	TestEqual(TEXT("The history/export shell must preserve the copy summary action id."), Config.UsageCostHistoryExportShellProfileDefinition.CopySummaryActionId, TEXT("copy-provider-usage-cost-summary"));
	TestTrue(TEXT("The history/export shell must include the history timeline panel."), HyperTwistWhisperCppPhase6RABTestInternal::ContainsPanelId(Config.UsageCostHistoryExportShellProfileDefinition.Panels, TEXT("history-timeline-card")));
	TestTrue(TEXT("The history/export shell must include the export preview action."), HyperTwistWhisperCppPhase6RABTestInternal::ContainsActionId(Config.UsageCostHistoryExportShellProfileDefinition.ActionBindings, TEXT("preview-provider-usage-cost-export")));
	return true;
}

IMPLEMENT_SIMPLE_AUTOMATION_TEST(
	FHyperTwistWhisperCppPhase6RABUsageCostHistoryExportShellStateTest,
	"HyperTwist.Permissive.WhisperCpp.Phase6R.AB.UsageCostHistoryExportShellState",
	EAutomationTestFlags::EditorContext | EAutomationTestFlags::EngineFilter
)

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

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

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

	const FHyperTwistTrainingCompanionSpeechSessionState SessionState =
		TrainingSubsystem->GetActiveCompanionSpeechSessionState();
	const FHyperTwistSpeechServiceHealth& Health = SessionState.ServiceHealth;
	const FHyperTwistSpeechUsageCostHistoryExportShellState& HistoryExport =
		SessionState.UsageCostHistoryExportShellState;

	TestTrue(TEXT("The service health must expose the usage/cost history shell."), Health.Capabilities.Contains(TEXT("providerUsageCostHistoryShell")));
	TestTrue(TEXT("The service health must expose the usage/cost export preview capability."), Health.Capabilities.Contains(TEXT("providerUsageCostExportPreview")));
	TestTrue(TEXT("The service health must expose the usage/cost summary copy capability."), Health.Capabilities.Contains(TEXT("providerUsageCostSummaryCopy")));

	TestTrue(TEXT("The history/export shell state must remain structurally valid."), HistoryExport.IsStructurallyValid());
	TestEqual(TEXT("The history/export shell must preserve the mock provider profile."), HistoryExport.ActiveProviderProfileId, TEXT("speech-provider/mock-offline-profile-v1"));
	TestEqual(TEXT("The history/export shell must retain exactly two bounded snapshots after open and submit."), HistoryExport.HistoryEntryCount, 2);
	TestEqual(TEXT("The history/export shell must preserve the latest source kind."), HistoryExport.LatestSourceKind, TEXT("post-transcript-health"));
	TestTrue(TEXT("The history/export shell must preserve export preview readiness."), HistoryExport.bExportPreviewReady);
	TestTrue(TEXT("The history/export shell must preserve copy-summary readiness."), HistoryExport.bCopySummaryReady);
	TestTrue(TEXT("The history/export shell must preserve the export preview action."), HistoryExport.AvailableActionIds.Contains(TEXT("preview-provider-usage-cost-export")));
	TestTrue(TEXT("The history/export shell must preserve the copy summary action."), HistoryExport.AvailableActionIds.Contains(TEXT("copy-provider-usage-cost-summary")));
	TestTrue(TEXT("The history/export shell must accumulate the mock usage quantity."), FMath::IsNearlyEqual(HistoryExport.TotalUsageQuantity, 1.50f));
	TestTrue(TEXT("The history/export shell must accumulate the mock estimated cost."), FMath::IsNearlyEqual(HistoryExport.TotalEstimatedCostUsd, 0.02f));
	TestEqual(TEXT("The history/export shell must preserve estimate-only entry count."), HistoryExport.EstimateOnlyEntryCount, 2);
	TestTrue(TEXT("The history/export preview text must preserve the bounded history count."), HistoryExport.ExportPreviewText.Contains(TEXT("historyEntryCount=2")));
	return true;
}

IMPLEMENT_SIMPLE_AUTOMATION_TEST(
	FHyperTwistWhisperCppPhase6RABProviderBackedHistoryExportFallbackTest,
	"HyperTwist.Permissive.WhisperCpp.Phase6R.AB.ProviderBackedHistoryExportFallback",
	EAutomationTestFlags::EditorContext | EAutomationTestFlags::EngineFilter
)

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

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

	HttpSpeechClient->ServiceBaseUrl.Reset();

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

	const FHyperTwistTrainingCompanionSpeechSessionState SessionState =
		TrainingSubsystem->GetActiveCompanionSpeechSessionState();
	const FHyperTwistSpeechUsageCostHistoryExportShellState& HistoryExport =
		SessionState.UsageCostHistoryExportShellState;

	TestTrue(TEXT("The provider-backed history/export fallback must remain structurally valid."), HistoryExport.IsStructurallyValid());
	TestEqual(TEXT("The fallback history/export shell must preserve the sidecar profile id."), HistoryExport.ActiveProviderProfileId, TEXT("speech-provider/local-http-sidecar-profile-v1"));
	TestEqual(TEXT("The fallback history/export shell must preserve the fallback source kind."), HistoryExport.LatestSourceKind, TEXT("provider-fallback-health"));
	TestEqual(TEXT("The fallback history/export shell must preserve one history entry."), HistoryExport.HistoryEntryCount, 1);
	TestEqual(TEXT("The fallback history/export shell must surface one active issue."), HistoryExport.ActiveIssueCount, 1);
	TestEqual(TEXT("The fallback history/export shell must surface the route-degraded issue kind."), HistoryExport.ActiveIssue.IssueKind, TEXT("route-degraded"));
	TestTrue(TEXT("The fallback history/export shell must still expose export preview readiness for first-party summary output."), HistoryExport.bExportPreviewReady);
	TestTrue(TEXT("The fallback history/export preview text must preserve the missing-endpoint reason."), HistoryExport.ExportPreviewText.Contains(TEXT("service-base-url-missing")));
	return true;
}

#endif
