// 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 HyperTwistWhisperCppPhase6RADTestInternal
{
	FHyperTwistTrainingDeck MakeSpeechDeck()
	{
		FHyperTwistTrainingDeck Deck;
		Deck.DeckId = TEXT("phase6r-ad/provider-billing-settlement");
		Deck.Title = TEXT("Phase 6R-AD Provider Billing Settlement");
		Deck.DeliveryModes = {
			EHyperTwistTrainingDeliveryMode::CoachReviewed
		};

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

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

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

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

	TestTrue(TEXT("The billing-settlement session config must remain structurally valid."), Config.IsStructurallyValid());
	TestEqual(TEXT("The billing-settlement shell profile id must be present."), Config.ProviderBillingSettlementShellProfileId, TEXT("speech-provider-billing-settlement-shell-v1"));
	TestTrue(TEXT("The billing-settlement shell profile must remain structurally valid."), Config.ProviderBillingSettlementShellProfileDefinition.IsStructurallyValid());
	TestEqual(TEXT("The billing-settlement shell must preserve the operator-facing shell kind."), Config.ProviderBillingSettlementShellProfileDefinition.ShellKind, TEXT("operator-provider-billing-settlement"));
	TestEqual(TEXT("The billing-settlement shell must preserve the invoice reconciliation action id."), Config.ProviderBillingSettlementShellProfileDefinition.InvoiceReconciliationActionId, TEXT("inspect-provider-invoice-reconciliation"));
	TestEqual(TEXT("The billing-settlement shell must preserve the readiness review action id."), Config.ProviderBillingSettlementShellProfileDefinition.SettlementReadinessActionId, TEXT("review-provider-settlement-readiness"));
	TestTrue(TEXT("The billing-settlement shell must include the settlement timeline panel."), HyperTwistWhisperCppPhase6RADTestInternal::ContainsPanelId(Config.ProviderBillingSettlementShellProfileDefinition.Panels, TEXT("settlement-timeline-card")));
	TestTrue(TEXT("The billing-settlement shell must include the invoice reconciliation action."), HyperTwistWhisperCppPhase6RADTestInternal::ContainsActionId(Config.ProviderBillingSettlementShellProfileDefinition.ActionBindings, TEXT("inspect-provider-invoice-reconciliation")));
	return true;
}

IMPLEMENT_SIMPLE_AUTOMATION_TEST(
	FHyperTwistWhisperCppPhase6RADProviderBillingSettlementShellStateTest,
	"HyperTwist.Permissive.WhisperCpp.Phase6R.AD.ProviderBillingSettlementShellState",
	EAutomationTestFlags::EditorContext | EAutomationTestFlags::EngineFilter
)

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

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

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

	const FHyperTwistTrainingCompanionSpeechSessionState SessionState =
		TrainingSubsystem->GetActiveCompanionSpeechSessionState();
	const FHyperTwistSpeechServiceHealth& Health = SessionState.ServiceHealth;
	const FHyperTwistSpeechProviderBillingSettlementShellState& Settlement =
		SessionState.ProviderBillingSettlementShellState;

	TestTrue(TEXT("The service health must expose the billing-settlement shell."), Health.Capabilities.Contains(TEXT("providerBillingSettlementShell")));
	TestTrue(TEXT("The service health must expose invoice reconciliation."), Health.Capabilities.Contains(TEXT("providerInvoiceReconciliation")));
	TestTrue(TEXT("The service health must expose settlement readiness review."), Health.Capabilities.Contains(TEXT("providerSettlementReadinessReview")));

	TestTrue(TEXT("The billing-settlement shell state must remain structurally valid."), Settlement.IsStructurallyValid());
	TestEqual(TEXT("The billing-settlement shell must preserve the mock provider profile."), Settlement.ActiveProviderProfileId, TEXT("speech-provider/mock-offline-profile-v1"));
	TestEqual(TEXT("The billing-settlement shell must retain exactly two bounded settlement entries after open and submit."), Settlement.SettlementEntryCount, 2);
	TestEqual(TEXT("The billing-settlement shell must preserve the latest source kind."), Settlement.LatestSourceKind, TEXT("receipt-review-derived-estimate-only"));
	TestTrue(TEXT("The billing-settlement shell must preserve summary readiness."), Settlement.bSettlementSummaryReady);
	TestFalse(TEXT("The billing-settlement shell must not mark invoice reconciliation ready before provider-posted charges appear."), Settlement.bInvoiceReconciliationReady);
	TestTrue(TEXT("The billing-settlement shell must preserve readiness-review visibility."), Settlement.bSettlementReadinessReviewReady);
	TestTrue(TEXT("The billing-settlement shell must preserve the invoice reconciliation action."), Settlement.AvailableActionIds.Contains(TEXT("inspect-provider-invoice-reconciliation")));
	TestTrue(TEXT("The billing-settlement shell must preserve the readiness review action."), Settlement.AvailableActionIds.Contains(TEXT("review-provider-settlement-readiness")));
	TestEqual(TEXT("The billing-settlement shell must preserve zero provider-posted charges in the mock route."), Settlement.ProviderPostedChargeCount, 0);
	TestEqual(TEXT("The billing-settlement shell must preserve zero reconciliation-ready entries in the mock route."), Settlement.ReconciliationReadyEntryCount, 0);
	TestEqual(TEXT("The billing-settlement shell must preserve the estimate-only entry count."), Settlement.EstimateOnlyEntryCount, 2);
	TestEqual(TEXT("The billing-settlement shell must preserve the blocked-settlement entry count."), Settlement.BlockedSettlementEntryCount, 2);
	TestTrue(TEXT("The billing-settlement shell must accumulate the mock estimated cost."), FMath::IsNearlyEqual(Settlement.TotalEstimatedCostUsd, 0.02f));
	TestTrue(TEXT("The billing-settlement shell must preserve zero settlement delta while no provider charge is posted."), FMath::IsNearlyEqual(Settlement.TotalSettlementDeltaUsd, 0.0f));
	TestEqual(TEXT("The billing-settlement shell must surface the pending provider-charge issue."), Settlement.ActiveIssue.IssueKind, TEXT("provider-charge-pending"));
	TestTrue(TEXT("The billing-settlement summary text must preserve the bounded reconciliation-ready count."), Settlement.SettlementSummaryText.Contains(TEXT("reconciliationReadyEntryCount=0")));
	return true;
}

IMPLEMENT_SIMPLE_AUTOMATION_TEST(
	FHyperTwistWhisperCppPhase6RADProviderBackedBillingSettlementFallbackTest,
	"HyperTwist.Permissive.WhisperCpp.Phase6R.AD.ProviderBackedBillingSettlementFallback",
	EAutomationTestFlags::EditorContext | EAutomationTestFlags::EngineFilter
)

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

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

	HttpSpeechClient->ServiceBaseUrl.Reset();

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

	const FHyperTwistTrainingCompanionSpeechSessionState SessionState =
		TrainingSubsystem->GetActiveCompanionSpeechSessionState();
	const FHyperTwistSpeechProviderBillingSettlementShellState& Settlement =
		SessionState.ProviderBillingSettlementShellState;

	TestTrue(TEXT("The provider-backed billing-settlement fallback must remain structurally valid."), Settlement.IsStructurallyValid());
	TestEqual(TEXT("The fallback billing-settlement shell must preserve the sidecar profile id."), Settlement.ActiveProviderProfileId, TEXT("speech-provider/local-http-sidecar-profile-v1"));
	TestEqual(TEXT("The fallback billing-settlement shell must preserve the fallback source kind."), Settlement.LatestSourceKind, TEXT("receipt-review-fallback-health"));
	TestEqual(TEXT("The fallback billing-settlement shell must preserve one settlement entry."), Settlement.SettlementEntryCount, 1);
	TestEqual(TEXT("The fallback billing-settlement shell must surface one active issue."), Settlement.ActiveIssueCount, 1);
	TestEqual(TEXT("The fallback billing-settlement shell must surface the route-degraded issue kind."), Settlement.ActiveIssue.IssueKind, TEXT("route-degraded"));
	TestTrue(TEXT("The fallback billing-settlement shell must still expose summary readiness for bounded inspection output."), Settlement.bSettlementSummaryReady);
	TestFalse(TEXT("The fallback billing-settlement shell must preserve invoice reconciliation as not ready."), Settlement.bInvoiceReconciliationReady);
	TestTrue(TEXT("The fallback billing-settlement summary text must preserve the missing-endpoint reason."), Settlement.SettlementSummaryText.Contains(TEXT("service-base-url-missing")));
	return true;
}

#endif
