// 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 HyperTwistWhisperCppPhase6RAATestInternal
{
	FHyperTwistTrainingDeck MakeSpeechDeck()
	{
		FHyperTwistTrainingDeck Deck;
		Deck.DeckId = TEXT("phase6r-aa/provider-usage-cost-dashboard");
		Deck.Title = TEXT("Phase 6R-AA Provider Usage/Cost Dashboard");
		Deck.DeliveryModes = {
			EHyperTwistTrainingDeliveryMode::CoachReviewed
		};

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

	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(
	FHyperTwistWhisperCppPhase6RAAUsageCostDashboardSessionConfigTest,
	"HyperTwist.Permissive.WhisperCpp.Phase6R.AA.UsageCostDashboardSessionConfig",
	EAutomationTestFlags::EditorContext | EAutomationTestFlags::EngineFilter
)

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

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

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

	TestTrue(TEXT("The dashboard session config must remain structurally valid."), Config.IsStructurallyValid());
	TestEqual(TEXT("The dashboard shell profile id must be present."), Config.UsageCostDashboardShellProfileId, TEXT("speech-provider-usage-cost-dashboard-shell-v1"));
	TestTrue(TEXT("The dashboard shell profile must remain structurally valid."), Config.UsageCostDashboardShellProfileDefinition.IsStructurallyValid());
	TestEqual(TEXT("The dashboard shell must preserve the operator-facing shell kind."), Config.UsageCostDashboardShellProfileDefinition.ShellKind, TEXT("operator-usage-cost-dashboard"));
	TestEqual(TEXT("The dashboard shell must preserve the refresh action id."), Config.UsageCostDashboardShellProfileDefinition.RefreshActionId, TEXT("refresh-provider-usage-cost-dashboard"));
	TestEqual(TEXT("The dashboard shell must preserve the route inspect action id."), Config.UsageCostDashboardShellProfileDefinition.RouteInspectActionId, TEXT("inspect-provider-route"));
	TestTrue(TEXT("The dashboard shell must support quota escalation banners."), Config.UsageCostDashboardShellProfileDefinition.bSupportsQuotaEscalationBanner);
	TestTrue(TEXT("The dashboard shell must include the provider summary panel."), HyperTwistWhisperCppPhase6RAATestInternal::ContainsPanelId(Config.UsageCostDashboardShellProfileDefinition.Panels, TEXT("provider-summary-card")));
	TestTrue(TEXT("The dashboard shell must include the route diagnostics action."), HyperTwistWhisperCppPhase6RAATestInternal::ContainsActionId(Config.UsageCostDashboardShellProfileDefinition.ActionBindings, TEXT("inspect-provider-route")));
	return true;
}

IMPLEMENT_SIMPLE_AUTOMATION_TEST(
	FHyperTwistWhisperCppPhase6RAAUsageCostDashboardShellStateTest,
	"HyperTwist.Permissive.WhisperCpp.Phase6R.AA.UsageCostDashboardShellState",
	EAutomationTestFlags::EditorContext | EAutomationTestFlags::EngineFilter
)

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

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

	const FHyperTwistTrainingCompanionSpeechSessionState SessionState =
		TrainingSubsystem->GetActiveCompanionSpeechSessionState();
	const FHyperTwistSpeechServiceHealth& Health = SessionState.ServiceHealth;
	const FHyperTwistSpeechUsageCostDashboardShellState& Dashboard =
		SessionState.UsageCostDashboardShellState;

	TestTrue(TEXT("The service health must expose the usage/cost dashboard shell."), Health.Capabilities.Contains(TEXT("providerUsageCostDashboardShell")));
	TestTrue(TEXT("The service health must expose the quota escalation banner capability."), Health.Capabilities.Contains(TEXT("providerQuotaEscalationBanner")));
	TestTrue(TEXT("The service health must expose the route cost diagnostics capability."), Health.Capabilities.Contains(TEXT("providerRouteCostDiagnostics")));

	TestTrue(TEXT("The dashboard shell state must remain structurally valid."), Dashboard.IsStructurallyValid());
	TestEqual(TEXT("The dashboard shell must preserve the mock provider profile."), Dashboard.ActiveProviderProfileId, TEXT("speech-provider/mock-offline-profile-v1"));
	TestEqual(TEXT("The dashboard shell must preserve the ready route state."), Dashboard.ActiveRouteStateId, TEXT("route-ready"));
	TestTrue(TEXT("The dashboard shell must preserve estimate badge visibility."), Dashboard.bEstimateBadgeVisible);
	TestTrue(TEXT("The dashboard shell must preserve quota visibility."), Dashboard.bQuotaKnown);
	TestFalse(TEXT("The dashboard shell must not escalate healthy mock posture."), Dashboard.bEscalationBannerVisible);
	TestEqual(TEXT("The dashboard shell must preserve zero active issues on the healthy mock route."), Dashboard.ActiveIssueCount, 0);
	TestTrue(TEXT("The dashboard shell must preserve the refresh action."), Dashboard.AvailableActionIds.Contains(TEXT("refresh-provider-usage-cost-dashboard")));
	TestTrue(TEXT("The dashboard shell must preserve the budget review action."), Dashboard.AvailableActionIds.Contains(TEXT("review-provider-budget")));
	TestTrue(TEXT("The dashboard shell must surface the mock usage quantity."), FMath::IsNearlyEqual(Dashboard.DisplayedUsageQuantity, 0.75f));
	TestTrue(TEXT("The dashboard shell must surface the mock estimated cost."), FMath::IsNearlyEqual(Dashboard.DisplayedEstimatedCostUsd, 0.01f));
	return true;
}

IMPLEMENT_SIMPLE_AUTOMATION_TEST(
	FHyperTwistWhisperCppPhase6RAAProviderBackedDashboardFallbackTest,
	"HyperTwist.Permissive.WhisperCpp.Phase6R.AA.ProviderBackedDashboardFallback",
	EAutomationTestFlags::EditorContext | EAutomationTestFlags::EngineFilter
)

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

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

	HttpSpeechClient->ServiceBaseUrl.Reset();

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

	const FHyperTwistTrainingCompanionSpeechSessionState SessionState =
		TrainingSubsystem->GetActiveCompanionSpeechSessionState();
	const FHyperTwistSpeechUsageCostDashboardShellState& Dashboard =
		SessionState.UsageCostDashboardShellState;

	TestTrue(TEXT("The provider-backed dashboard fallback must remain structurally valid."), Dashboard.IsStructurallyValid());
	TestEqual(TEXT("The fallback dashboard must preserve the sidecar profile id."), Dashboard.ActiveProviderProfileId, TEXT("speech-provider/local-http-sidecar-profile-v1"));
	TestEqual(TEXT("The fallback dashboard must preserve the awaiting-endpoint route state."), Dashboard.ActiveRouteStateId, TEXT("route-awaiting-endpoint"));
	TestFalse(TEXT("The fallback dashboard must expose an unready route."), Dashboard.bRouteReady);
	TestFalse(TEXT("The fallback dashboard must keep quota unknown during route failure."), Dashboard.bQuotaKnown);
	TestTrue(TEXT("The fallback dashboard must escalate route failure posture."), Dashboard.bEscalationBannerVisible);
	TestEqual(TEXT("The fallback dashboard must surface one active issue."), Dashboard.ActiveIssueCount, 1);
	TestEqual(TEXT("The fallback dashboard must surface the route-degraded issue kind."), Dashboard.ActiveIssue.IssueKind, TEXT("route-degraded"));
	TestEqual(TEXT("The fallback dashboard must preserve the route inspect action."), Dashboard.ActiveIssue.RecommendedActionId, TEXT("inspect-provider-route"));
	TestTrue(TEXT("The fallback dashboard detail line must preserve the missing-endpoint reason."), Dashboard.DetailLine.Contains(TEXT("service-base-url-missing")));
	return true;
}

#endif
