#include "HyperTwistRecognition/HyperTwistSpeechClient.h"

#include "HyperTwistBootstrap/HyperTwistContractLibrary.h"
#include "Dom/JsonObject.h"
#include "Http.h"
#include "HttpManager.h"
#include "HttpModule.h"
#include "Interfaces/IHttpRequest.h"
#include "Interfaces/IHttpResponse.h"
#include "JsonObjectConverter.h"
#include "Serialization/JsonSerializer.h"
#include "Serialization/JsonWriter.h"

namespace HyperTwistHttpSpeechClientInternal
{
	template <typename TStruct>
	bool SerializeStruct(const TStruct& Value, FString& OutJson)
	{
		return FJsonObjectConverter::UStructToJsonObjectString(TStruct::StaticStruct(), &Value, OutJson, 0, 0);
	}

	template <typename TStruct>
	bool DeserializeStruct(const FString& Json, TStruct& OutValue)
	{
		return !Json.IsEmpty() && FJsonObjectConverter::JsonObjectStringToUStruct(Json, &OutValue, 0, 0);
	}

	FString MakeSessionIdJson(const FString& SessionId)
	{
		FString Json;
		const TSharedRef<FJsonObject> Root = MakeShared<FJsonObject>();
		Root->SetStringField(TEXT("sessionId"), SessionId);
		const TSharedRef<TJsonWriter<>> Writer = TJsonWriterFactory<>::Create(&Json);
		FJsonSerializer::Serialize(Root, Writer);
		return Json;
	}

	FString BuildUrl(const FString& BaseUrl, const FString& Path)
	{
		if (BaseUrl.IsEmpty())
		{
			return FString();
		}

		const FString TrimmedBase = BaseUrl.EndsWith(TEXT("/")) ? BaseUrl.LeftChop(1) : BaseUrl;
		if (Path.IsEmpty())
		{
			return TrimmedBase;
		}

		const FString TrimmedPath = Path.StartsWith(TEXT("/")) ? Path.RightChop(1) : Path;
		return FString::Printf(TEXT("%s/%s"), *TrimmedBase, *TrimmedPath);
	}

	const FHyperTwistSpeechProviderProfile* ResolveProviderProfile(
		const FHyperTwistSpeechSessionConfig* SessionConfig
	)
	{
		if (SessionConfig != nullptr
			&& SessionConfig->ProviderProfileDefinition.IsStructurallyValid())
		{
			return &SessionConfig->ProviderProfileDefinition;
		}

		return nullptr;
	}

	FString ResolveServiceBaseUrl(
		const UHyperTwistHttpSpeechClient& Client,
		const FHyperTwistSpeechSessionConfig* SessionConfig
	)
	{
		if (const FHyperTwistSpeechProviderProfile* Profile = ResolveProviderProfile(SessionConfig))
		{
			if (!Profile->EndpointBaseUrl.IsEmpty())
			{
				return Profile->EndpointBaseUrl;
			}
		}

		return Client.ServiceBaseUrl;
	}

	FString ResolveProviderLabel(
		const UHyperTwistHttpSpeechClient& Client,
		const FHyperTwistSpeechSessionConfig* SessionConfig
	)
	{
		if (const FHyperTwistSpeechProviderProfile* Profile = ResolveProviderProfile(SessionConfig))
		{
			if (!Profile->DisplayLabel.IsEmpty())
			{
				return Profile->DisplayLabel;
			}
		}

		return Client.ProviderLabel;
	}

	TArray<FString> BuildRetrievedHints(const FHyperTwistSpeechSessionConfig* SessionConfig)
	{
		TArray<FString> RetrievedHints;
		if (SessionConfig == nullptr
			|| !SessionConfig->OrchestrationProfile.bEnableRetrievedHintAugmentation)
		{
			return RetrievedHints;
		}

		const int32 MaxHintCount =
			FMath::Max(SessionConfig->OrchestrationProfile.MaxRetrievedHintCount, 0);
		for (const FString& CommandHint : SessionConfig->CommandHints)
		{
			if (!CommandHint.IsEmpty())
			{
				RetrievedHints.Add(CommandHint);
			}
			if (RetrievedHints.Num() >= MaxHintCount)
			{
				break;
			}
		}

		return RetrievedHints;
	}

	struct FHttpJsonResponse
	{
		bool bCompleted = false;
		bool bSucceeded = false;
		int32 StatusCode = 0;
		FString ResponseBody;
		FString Error;
	};

	bool ExecuteJsonRequest(
		const UHyperTwistHttpSpeechClient& Client,
		const FString& Verb,
		const FString& Url,
		const FString& RequestJson,
		FHttpJsonResponse& OutResponse)
	{
		const TSharedRef<FHttpJsonResponse, ESPMode::ThreadSafe> ResponseState =
			MakeShared<FHttpJsonResponse, ESPMode::ThreadSafe>();
		OutResponse = FHttpJsonResponse();

		if (Url.IsEmpty())
		{
			OutResponse.Error = TEXT("service-base-url-missing");
			return false;
		}

		const TSharedRef<IHttpRequest, ESPMode::ThreadSafe> Request = FHttpModule::Get().CreateRequest();
		Request->SetURL(Url);
		Request->SetVerb(Verb);
		Request->SetHeader(TEXT("Accept"), TEXT("application/json"));
		Request->SetHeader(TEXT("Content-Type"), TEXT("application/json"));

		if (!Client.AuthorizationToken.IsEmpty())
		{
			Request->SetHeader(TEXT("Authorization"), FString::Printf(TEXT("Bearer %s"), *Client.AuthorizationToken));
		}

		if (!RequestJson.IsEmpty())
		{
			Request->SetContentAsString(RequestJson);
		}

		Request->OnProcessRequestComplete().BindLambda(
			[ResponseState](FHttpRequestPtr, FHttpResponsePtr Response, bool bWasSuccessful)
			{
				ResponseState->bCompleted = true;

				if (Response.IsValid())
				{
					ResponseState->StatusCode = Response->GetResponseCode();
					ResponseState->ResponseBody = Response->GetContentAsString();
				}

				if (!bWasSuccessful)
				{
					ResponseState->Error = TEXT("request-failed");
					return;
				}

				if (!Response.IsValid())
				{
					ResponseState->Error = TEXT("response-missing");
					return;
				}

				if (!EHttpResponseCodes::IsOk(ResponseState->StatusCode))
				{
					ResponseState->Error = FString::Printf(TEXT("http-%d"), ResponseState->StatusCode);
					return;
				}

				ResponseState->bSucceeded = true;
			});

		if (!Request->ProcessRequest())
		{
			OutResponse.Error = TEXT("request-start-failed");
			return false;
		}

		const double TimeoutSeconds = FMath::Max(static_cast<double>(Client.RequestTimeoutSeconds), 0.1);
		const double Deadline = FPlatformTime::Seconds() + TimeoutSeconds;
		while (!ResponseState->bCompleted && FPlatformTime::Seconds() < Deadline)
		{
			FHttpModule::Get().GetHttpManager().Tick(0.01f);
			FPlatformProcess::Sleep(0.01f);
		}

		if (!ResponseState->bCompleted)
		{
			Request->OnProcessRequestComplete().Unbind();
			Request->CancelRequest();
			ResponseState->Error = TEXT("request-timeout");
			OutResponse = *ResponseState;
			return false;
		}

		OutResponse = *ResponseState;
		return OutResponse.bSucceeded;
	}
}

bool UHyperTwistHttpSpeechClient::OpenSpeechSession(const FHyperTwistSpeechSessionConfig& Config, FString& OutError)
{
	OutError.Reset();
	LastRequestedSessionConfig = Config;
	const FString EffectiveServiceBaseUrl =
		HyperTwistHttpSpeechClientInternal::ResolveServiceBaseUrl(*this, &Config);

	FString RequestJson;
	if (!HyperTwistHttpSpeechClientInternal::SerializeStruct(Config, RequestJson))
	{
		OutError = TEXT("request-serialize-failed");
		LastTransportError = OutError;
		return false;
	}

	HyperTwistHttpSpeechClientInternal::FHttpJsonResponse Response;
	if (!HyperTwistHttpSpeechClientInternal::ExecuteJsonRequest(
		*this,
		TEXT("POST"),
		HyperTwistHttpSpeechClientInternal::BuildUrl(EffectiveServiceBaseUrl, OpenSessionPath),
		RequestJson,
		Response))
	{
		OutError = Response.Error;
		LastTransportError = OutError;
		return false;
	}

	LastTransportError.Reset();
	SessionConfigs.Add(Config.SessionId, Config);
	return true;
}

FHyperTwistSpeechTranscriptResult UHyperTwistHttpSpeechClient::TranscribeSpeechUtterance(
	const FHyperTwistSpeechUtteranceEnvelope& Utterance
)
{
	FHyperTwistSpeechTranscriptResult Result;
	Result.SessionId = Utterance.SessionId;
	Result.UtteranceId = Utterance.UtteranceId;
	const FHyperTwistSpeechSessionConfig* SessionConfig = SessionConfigs.Find(Utterance.SessionId);
	const FString EffectiveServiceBaseUrl =
		HyperTwistHttpSpeechClientInternal::ResolveServiceBaseUrl(*this, SessionConfig);

	FString RequestJson;
	if (!HyperTwistHttpSpeechClientInternal::SerializeStruct(Utterance, RequestJson))
	{
		LastTransportError = TEXT("request-serialize-failed");
		Result.Warnings.Add(LastTransportError);
		return Result;
	}

	HyperTwistHttpSpeechClientInternal::FHttpJsonResponse Response;
	if (!HyperTwistHttpSpeechClientInternal::ExecuteJsonRequest(
		*this,
		TEXT("POST"),
		HyperTwistHttpSpeechClientInternal::BuildUrl(EffectiveServiceBaseUrl, TranscribeUtterancePath),
		RequestJson,
		Response))
	{
		LastTransportError = Response.Error;
		Result.Warnings.Add(LastTransportError);
		return Result;
	}

	if (!HyperTwistHttpSpeechClientInternal::DeserializeStruct(Response.ResponseBody, Result))
	{
		LastTransportError = TEXT("invalid-provider-response");
		Result = FHyperTwistSpeechTranscriptResult();
		Result.SessionId = Utterance.SessionId;
		Result.UtteranceId = Utterance.UtteranceId;
		Result.Warnings.Add(LastTransportError);
		return Result;
	}

	if (Result.SessionId.IsEmpty())
	{
		Result.SessionId = Utterance.SessionId;
	}
	if (Result.UtteranceId.IsEmpty())
	{
		Result.UtteranceId = Utterance.UtteranceId;
	}
	if (SessionConfig != nullptr)
	{
		if (Result.TaskKind.IsEmpty())
		{
			Result.TaskKind = SessionConfig->TaskKind;
		}
		if (Result.GrammarProfileId.IsEmpty())
		{
			Result.GrammarProfileId = SessionConfig->GrammarProfileId;
		}
		if (Result.OrchestrationProfileId.IsEmpty())
		{
			Result.OrchestrationProfileId = SessionConfig->OrchestrationProfile.OrchestrationProfileId;
		}
		if (Result.ServiceLaneId.IsEmpty())
		{
			Result.ServiceLaneId = SessionConfig->OrchestrationProfile.ServiceLaneId;
		}
		if (Result.RequestedBatchSize <= 0)
		{
			Result.RequestedBatchSize = SessionConfig->OrchestrationProfile.PreferredBatchSize;
		}
		if (Result.ProcessedClipCount <= 0)
		{
			Result.ProcessedClipCount = 1;
		}
		if (Result.AppliedBatchCollectionWindowMs <= 0)
		{
			Result.AppliedBatchCollectionWindowMs =
				SessionConfig->OrchestrationProfile.BatchCollectionWindowMs;
		}
		Result.bWordTimestampsRequested =
			Result.bWordTimestampsRequested || SessionConfig->OrchestrationProfile.bEnableWordTimestamps;
		Result.bConditionedOnPreviousText =
			Result.bConditionedOnPreviousText || SessionConfig->OrchestrationProfile.bConditionOnPreviousText;
		Result.bUsedBatchedInference =
			Result.bUsedBatchedInference || SessionConfig->OrchestrationProfile.bEnableBatchedInference;
		if (Result.AppliedPromptRoutingModeId.IsEmpty())
		{
			Result.AppliedPromptRoutingModeId =
				SessionConfig->OrchestrationProfile.PromptRoutingModeId;
		}
		if (Result.AppliedPrefixHint.IsEmpty())
		{
			Result.AppliedPrefixHint = SessionConfig->OrchestrationProfile.PrefixHint;
		}
		if (Result.AppliedHotwordHints.Num() <= 0)
		{
			Result.AppliedHotwordHints = SessionConfig->OrchestrationProfile.HotwordHints;
		}
		if (Result.AppliedRetrievalContextLaneId.IsEmpty())
		{
			Result.AppliedRetrievalContextLaneId =
				SessionConfig->OrchestrationProfile.RetrievalContextLaneId;
		}
		if (Result.AppliedRetrievedHints.Num() <= 0)
		{
			Result.AppliedRetrievedHints =
				HyperTwistHttpSpeechClientInternal::BuildRetrievedHints(SessionConfig);
		}
		Result.RetrievedHintCount = Result.AppliedRetrievedHints.Num();
		Result.bUsedRetrievedHintAugmentation =
			Result.bUsedRetrievedHintAugmentation || Result.RetrievedHintCount > 0;
		Result.bUsedPromptHints =
			Result.bUsedPromptHints
			|| !Result.AppliedPrefixHint.IsEmpty()
			|| Result.AppliedHotwordHints.Num() > 0
			|| Result.bUsedRetrievedHintAugmentation;
		if (Result.LanguageProbability <= 0.0f
			&& !SessionConfig->LanguageMode.IsEmpty()
			&& !SessionConfig->LanguageMode.Equals(TEXT("auto"), ESearchCase::IgnoreCase))
		{
			Result.LanguageProbability = 1.0f;
		}
	}

	LastTransportError.Reset();
	return Result;
}

bool UHyperTwistHttpSpeechClient::CloseSpeechSession(const FString& SessionId, FString& OutError)
{
	OutError.Reset();
	const FHyperTwistSpeechSessionConfig* SessionConfig = SessionConfigs.Find(SessionId);
	const FString EffectiveServiceBaseUrl =
		HyperTwistHttpSpeechClientInternal::ResolveServiceBaseUrl(*this, SessionConfig);

	HyperTwistHttpSpeechClientInternal::FHttpJsonResponse Response;
	if (!HyperTwistHttpSpeechClientInternal::ExecuteJsonRequest(
		*this,
		TEXT("POST"),
		HyperTwistHttpSpeechClientInternal::BuildUrl(EffectiveServiceBaseUrl, CloseSessionPath),
		HyperTwistHttpSpeechClientInternal::MakeSessionIdJson(SessionId),
		Response))
	{
		OutError = Response.Error;
		LastTransportError = OutError;
		return false;
	}

	LastTransportError.Reset();
	SessionConfigs.Remove(SessionId);
	return true;
}

FHyperTwistSpeechServiceHealth UHyperTwistHttpSpeechClient::GetSpeechServiceHealth() const
{
	FHyperTwistSpeechServiceHealth Health = UHyperTwistContractLibrary::MakeMockSpeechServiceHealth();
	const FHyperTwistSpeechSessionConfig* HealthSessionConfig = nullptr;
	for (auto It = SessionConfigs.CreateConstIterator(); It; ++It)
	{
		HealthSessionConfig = &It.Value();
		break;
	}
	if (HealthSessionConfig == nullptr && LastRequestedSessionConfig.IsStructurallyValid())
	{
		HealthSessionConfig = &LastRequestedSessionConfig;
	}

	const FHyperTwistSpeechSessionConfig ProviderDefaults =
		HealthSessionConfig != nullptr && HealthSessionConfig->IsStructurallyValid()
			? *HealthSessionConfig
			: UHyperTwistContractLibrary::MakeSampleSpeechSessionConfig();
	const FString EffectiveProviderLabel =
		HyperTwistHttpSpeechClientInternal::ResolveProviderLabel(*this, HealthSessionConfig);
	const FString EffectiveServiceBaseUrl =
		HyperTwistHttpSpeechClientInternal::ResolveServiceBaseUrl(*this, HealthSessionConfig);
	Health.ProviderLabel = EffectiveProviderLabel;
	Health.ServiceVersion = TEXT("provider-unavailable/v1");
	Health.ServiceEndpoint = EffectiveServiceBaseUrl;
	Health.bReady = false;
	Health.Capabilities = {
		TEXT("transport:http"),
		TEXT("provider-backed-speech"),
		TEXT("transcribe"),
		TEXT("vadSegments"),
		TEXT("grammarHints"),
		TEXT("microphoneCaptureShell"),
		TEXT("devicePermissionShell"),
		TEXT("captureRouteReadinessShell"),
		TEXT("captureRouteRetry"),
		TEXT("devicePermissionWorkflow"),
		TEXT("devicePermissionSettingsHandoff"),
		TEXT("devicePermissionRecheck"),
		TEXT("nativeCaptureRouteWorkflow"),
		TEXT("nativeCaptureRouteWorkflowShell"),
		TEXT("captureRoutePreparationControl"),
		TEXT("captureRouteOwnershipAssessment"),
		TEXT("captureRouteOwnershipSummaryCard"),
		TEXT("captureRoutePreparationCard"),
		TEXT("captureRouteSessionReopenCard"),
		TEXT("reopenSpeechSession"),
		TEXT("streamingPreview"),
		TEXT("manualTranscriptCommit"),
		TEXT("batchedTranscribe"),
		TEXT("batchWindowTuning"),
		TEXT("wordTimestamps"),
		TEXT("languageDetection"),
		TEXT("promptHints"),
		TEXT("promptRoutingProfiles"),
		TEXT("retrievalHintAugmentation"),
		TEXT("providerProfileCustody"),
		TEXT("byokCustody"),
		TEXT("providerRoutingPolicy"),
		TEXT("providerRouteSelection"),
		TEXT("workflowPolicyState"),
		TEXT("openAiCompatibleCustomEndpointProfile"),
		TEXT("userLabeledByokProfiles"),
		TEXT("downloadableModelPayloadCustody"),
		TEXT("payloadIntegrityReview"),
		TEXT("normalizedUsageEvents"),
		TEXT("normalizedCostEvents"),
		TEXT("quotaRateLimitState"),
		TEXT("providerUsageCostDashboardShell"),
		TEXT("providerQuotaEscalationBanner"),
		TEXT("providerRouteCostDiagnostics"),
		TEXT("providerUsageCostHistoryShell"),
		TEXT("providerUsageCostExportPreview"),
		TEXT("providerUsageCostSummaryCopy"),
		TEXT("providerReceiptReviewShell"),
		TEXT("providerPostedChargeInspection"),
		TEXT("providerChargeVarianceReview"),
		TEXT("providerBillingSettlementShell"),
		TEXT("providerInvoiceReconciliation"),
		TEXT("providerSettlementReadinessReview"),
		TEXT("providerSettlementExceptionShell"),
		TEXT("providerExternalPortalHandoff"),
		TEXT("providerSettlementExceptionReview")
	};
	Health.SupportedOrchestrationProfiles = {
		TEXT("python-batch-transcribe-v1")
	};

	HyperTwistHttpSpeechClientInternal::FHttpJsonResponse Response;
	if (!HyperTwistHttpSpeechClientInternal::ExecuteJsonRequest(
		*this,
		TEXT("GET"),
		HyperTwistHttpSpeechClientInternal::BuildUrl(EffectiveServiceBaseUrl, HealthPath),
		FString(),
		Response))
	{
		LastTransportError = Response.Error;
		Health.ProviderProfileId = ProviderDefaults.ProviderProfileId;
		Health.ProviderProfileDefinition = ProviderDefaults.ProviderProfileDefinition;
		Health.ProviderProfileDefinition.DisplayLabel = EffectiveProviderLabel.IsEmpty()
			? Health.ProviderProfileDefinition.DisplayLabel
			: EffectiveProviderLabel;
		Health.ProviderProfileDefinition.EndpointBaseUrl = EffectiveServiceBaseUrl;
		Health.ByokCustodyProfileId = ProviderDefaults.ByokCustodyProfileId;
		Health.ByokCustodyProfileDefinition = ProviderDefaults.ByokCustodyProfileDefinition;
		Health.ProviderRoutingPolicyId = ProviderDefaults.ProviderRoutingPolicyId;
		Health.ProviderRoutingPolicyDefinition = ProviderDefaults.ProviderRoutingPolicyDefinition;
		Health.ProviderRouteDecision = ProviderDefaults.ProviderRouteDecision;
		Health.ProviderRouteDecision.RouteStateId = EffectiveServiceBaseUrl.IsEmpty()
			? TEXT("route-awaiting-endpoint")
			: TEXT("route-health-degraded");
		Health.ProviderRouteDecision.DecisionReason = EffectiveServiceBaseUrl.IsEmpty()
			? TEXT("provider-backed-sidecar-route-unavailable")
			: TEXT("provider-backed-sidecar-health-degraded");
		Health.ProviderRouteDecision.FailureReason = LastTransportError;
		Health.ProviderRouteDecision.bUsedFallbackHealthPosture = true;
		Health.ProviderRouteDecision.bRouteReady = false;
		Health.LastError = LastTransportError;
		return Health;
	}

	if (!HyperTwistHttpSpeechClientInternal::DeserializeStruct(Response.ResponseBody, Health))
	{
		LastTransportError = TEXT("invalid-provider-response");
		Health = UHyperTwistContractLibrary::MakeMockSpeechServiceHealth();
		Health.ProviderLabel = EffectiveProviderLabel;
		Health.ServiceVersion = TEXT("provider-unavailable/v1");
		Health.ServiceEndpoint = EffectiveServiceBaseUrl;
		Health.bReady = false;
		Health.Capabilities = {
			TEXT("transport:http"),
			TEXT("provider-backed-speech"),
			TEXT("transcribe"),
			TEXT("vadSegments"),
			TEXT("grammarHints"),
			TEXT("microphoneCaptureShell"),
			TEXT("devicePermissionShell"),
			TEXT("captureRouteReadinessShell"),
			TEXT("captureRouteRetry"),
		TEXT("devicePermissionWorkflow"),
		TEXT("devicePermissionSettingsHandoff"),
		TEXT("devicePermissionRecheck"),
		TEXT("nativeCaptureRouteWorkflow"),
		TEXT("nativeCaptureRouteWorkflowShell"),
		TEXT("captureRoutePreparationControl"),
		TEXT("captureRouteOwnershipAssessment"),
		TEXT("captureRouteOwnershipSummaryCard"),
		TEXT("captureRoutePreparationCard"),
		TEXT("captureRouteSessionReopenCard"),
		TEXT("reopenSpeechSession"),
			TEXT("streamingPreview"),
			TEXT("manualTranscriptCommit"),
			TEXT("batchedTranscribe"),
			TEXT("wordTimestamps"),
			TEXT("languageDetection"),
			TEXT("promptHints"),
			TEXT("providerProfileCustody"),
			TEXT("byokCustody"),
			TEXT("providerRoutingPolicy"),
			TEXT("providerRouteSelection"),
			TEXT("workflowPolicyState"),
			TEXT("openAiCompatibleCustomEndpointProfile"),
			TEXT("userLabeledByokProfiles"),
			TEXT("downloadableModelPayloadCustody"),
			TEXT("payloadIntegrityReview"),
			TEXT("normalizedUsageEvents"),
			TEXT("normalizedCostEvents"),
			TEXT("quotaRateLimitState"),
			TEXT("providerUsageCostDashboardShell"),
			TEXT("providerQuotaEscalationBanner"),
			TEXT("providerRouteCostDiagnostics"),
			TEXT("providerUsageCostHistoryShell"),
			TEXT("providerUsageCostExportPreview"),
			TEXT("providerUsageCostSummaryCopy"),
			TEXT("providerReceiptReviewShell"),
			TEXT("providerPostedChargeInspection"),
			TEXT("providerChargeVarianceReview"),
			TEXT("providerBillingSettlementShell"),
			TEXT("providerInvoiceReconciliation"),
			TEXT("providerSettlementReadinessReview"),
			TEXT("providerSettlementExceptionShell"),
			TEXT("providerExternalPortalHandoff"),
			TEXT("providerSettlementExceptionReview")
		};
		Health.SupportedOrchestrationProfiles = {
			TEXT("python-batch-transcribe-v1")
		};
		Health.ProviderProfileId = ProviderDefaults.ProviderProfileId;
		Health.ProviderProfileDefinition = ProviderDefaults.ProviderProfileDefinition;
		Health.ProviderProfileDefinition.DisplayLabel = EffectiveProviderLabel.IsEmpty()
			? Health.ProviderProfileDefinition.DisplayLabel
			: EffectiveProviderLabel;
		Health.ProviderProfileDefinition.EndpointBaseUrl = EffectiveServiceBaseUrl;
		Health.ByokCustodyProfileId = ProviderDefaults.ByokCustodyProfileId;
		Health.ByokCustodyProfileDefinition = ProviderDefaults.ByokCustodyProfileDefinition;
		Health.ProviderRoutingPolicyId = ProviderDefaults.ProviderRoutingPolicyId;
		Health.ProviderRoutingPolicyDefinition = ProviderDefaults.ProviderRoutingPolicyDefinition;
		Health.ProviderRouteDecision = ProviderDefaults.ProviderRouteDecision;
		Health.ProviderRouteDecision.RouteStateId = TEXT("route-health-degraded");
		Health.ProviderRouteDecision.DecisionReason = TEXT("provider-backed-sidecar-health-degraded");
		Health.ProviderRouteDecision.FailureReason = LastTransportError;
		Health.ProviderRouteDecision.bUsedFallbackHealthPosture = true;
		Health.ProviderRouteDecision.bRouteReady = false;
		Health.LastError = LastTransportError;
		return Health;
	}

	if (Health.ProviderLabel.IsEmpty())
	{
		Health.ProviderLabel = EffectiveProviderLabel;
	}
	Health.Capabilities.AddUnique(TEXT("microphoneCaptureShell"));
	Health.Capabilities.AddUnique(TEXT("devicePermissionShell"));
	Health.Capabilities.AddUnique(TEXT("captureRouteReadinessShell"));
	Health.Capabilities.AddUnique(TEXT("captureRouteRetry"));
	Health.Capabilities.AddUnique(TEXT("devicePermissionWorkflow"));
	Health.Capabilities.AddUnique(TEXT("devicePermissionSettingsHandoff"));
	Health.Capabilities.AddUnique(TEXT("devicePermissionRecheck"));
	Health.Capabilities.AddUnique(TEXT("nativeCaptureRouteWorkflow"));
	Health.Capabilities.AddUnique(TEXT("nativeCaptureRouteWorkflowShell"));
	Health.Capabilities.AddUnique(TEXT("captureRoutePreparationControl"));
	Health.Capabilities.AddUnique(TEXT("captureRouteOwnershipAssessment"));
	Health.Capabilities.AddUnique(TEXT("captureRouteOwnershipSummaryCard"));
	Health.Capabilities.AddUnique(TEXT("captureRoutePreparationCard"));
	Health.Capabilities.AddUnique(TEXT("captureRouteSessionReopenCard"));
	Health.Capabilities.AddUnique(TEXT("reopenSpeechSession"));
	Health.Capabilities.AddUnique(TEXT("streamingPreview"));
	Health.Capabilities.AddUnique(TEXT("manualTranscriptCommit"));
	Health.SupportedOrchestrationProfiles.AddUnique(TEXT("python-batch-transcribe-v1"));
	if (Health.ServiceEndpoint.IsEmpty())
	{
		Health.ServiceEndpoint = EffectiveServiceBaseUrl;
	}

	Health.Capabilities.AddUnique(TEXT("transport:http"));
	Health.Capabilities.AddUnique(TEXT("provider-backed-speech"));
	Health.Capabilities.AddUnique(TEXT("batchedTranscribe"));
	Health.Capabilities.AddUnique(TEXT("batchWindowTuning"));
	Health.Capabilities.AddUnique(TEXT("wordTimestamps"));
	Health.Capabilities.AddUnique(TEXT("languageDetection"));
	Health.Capabilities.AddUnique(TEXT("promptHints"));
	Health.Capabilities.AddUnique(TEXT("promptRoutingProfiles"));
	Health.Capabilities.AddUnique(TEXT("retrievalHintAugmentation"));
	Health.Capabilities.AddUnique(TEXT("providerProfileCustody"));
	Health.Capabilities.AddUnique(TEXT("byokCustody"));
	Health.Capabilities.AddUnique(TEXT("providerRoutingPolicy"));
	Health.Capabilities.AddUnique(TEXT("providerRouteSelection"));
	Health.Capabilities.AddUnique(TEXT("workflowPolicyState"));
	Health.Capabilities.AddUnique(TEXT("openAiCompatibleCustomEndpointProfile"));
	Health.Capabilities.AddUnique(TEXT("userLabeledByokProfiles"));
	Health.Capabilities.AddUnique(TEXT("downloadableModelPayloadCustody"));
	Health.Capabilities.AddUnique(TEXT("payloadIntegrityReview"));
	Health.Capabilities.AddUnique(TEXT("normalizedUsageEvents"));
	Health.Capabilities.AddUnique(TEXT("normalizedCostEvents"));
	Health.Capabilities.AddUnique(TEXT("quotaRateLimitState"));
	Health.Capabilities.AddUnique(TEXT("providerUsageCostDashboardShell"));
	Health.Capabilities.AddUnique(TEXT("providerQuotaEscalationBanner"));
	Health.Capabilities.AddUnique(TEXT("providerRouteCostDiagnostics"));
	Health.Capabilities.AddUnique(TEXT("providerUsageCostHistoryShell"));
	Health.Capabilities.AddUnique(TEXT("providerUsageCostExportPreview"));
	Health.Capabilities.AddUnique(TEXT("providerUsageCostSummaryCopy"));
	Health.Capabilities.AddUnique(TEXT("providerReceiptReviewShell"));
	Health.Capabilities.AddUnique(TEXT("providerPostedChargeInspection"));
	Health.Capabilities.AddUnique(TEXT("providerChargeVarianceReview"));
	Health.Capabilities.AddUnique(TEXT("providerBillingSettlementShell"));
	Health.Capabilities.AddUnique(TEXT("providerInvoiceReconciliation"));
	Health.Capabilities.AddUnique(TEXT("providerSettlementReadinessReview"));
	Health.Capabilities.AddUnique(TEXT("providerSettlementExceptionShell"));
	Health.Capabilities.AddUnique(TEXT("providerExternalPortalHandoff"));
	Health.Capabilities.AddUnique(TEXT("providerSettlementExceptionReview"));
	Health.SupportedOrchestrationProfiles.AddUnique(TEXT("python-batch-transcribe-v1"));
	if (Health.ProviderProfileId.IsEmpty())
	{
		Health.ProviderProfileId = ProviderDefaults.ProviderProfileId;
	}
	if (!Health.ProviderProfileDefinition.IsStructurallyValid())
	{
		Health.ProviderProfileDefinition = ProviderDefaults.ProviderProfileDefinition;
	}
	Health.ProviderProfileDefinition.DisplayLabel = EffectiveProviderLabel.IsEmpty()
		? Health.ProviderProfileDefinition.DisplayLabel
		: EffectiveProviderLabel;
	Health.ProviderProfileDefinition.EndpointBaseUrl = EffectiveServiceBaseUrl;
	if (Health.ByokCustodyProfileId.IsEmpty())
	{
		Health.ByokCustodyProfileId = ProviderDefaults.ByokCustodyProfileId;
	}
	if (!Health.ByokCustodyProfileDefinition.IsStructurallyValid())
	{
		Health.ByokCustodyProfileDefinition = ProviderDefaults.ByokCustodyProfileDefinition;
	}
	if (Health.ProviderRoutingPolicyId.IsEmpty())
	{
		Health.ProviderRoutingPolicyId = ProviderDefaults.ProviderRoutingPolicyId;
	}
	if (!Health.ProviderRoutingPolicyDefinition.IsStructurallyValid())
	{
		Health.ProviderRoutingPolicyDefinition = ProviderDefaults.ProviderRoutingPolicyDefinition;
	}
	if (!Health.ProviderRouteDecision.IsStructurallyValid())
	{
		Health.ProviderRouteDecision = ProviderDefaults.ProviderRouteDecision;
	}
	if (Health.ProviderRouteDecision.SelectedProviderProfileId.IsEmpty())
	{
		Health.ProviderRouteDecision.SelectedProviderProfileId = Health.ProviderProfileId;
	}
	if (Health.ProviderRouteDecision.RequestedProviderProfileId.IsEmpty())
	{
		Health.ProviderRouteDecision.RequestedProviderProfileId = Health.ProviderProfileId;
	}
	if (Health.ProviderRouteDecision.SelectedProviderClass.IsEmpty())
	{
		Health.ProviderRouteDecision.SelectedProviderClass =
			Health.ProviderProfileDefinition.ProviderClass;
	}
	if (Health.ProviderRouteDecision.SelectedEndpointClass.IsEmpty())
	{
		Health.ProviderRouteDecision.SelectedEndpointClass =
			Health.ProviderProfileDefinition.EndpointClass;
	}
	if (Health.ProviderRouteDecision.SelectedTransportKind.IsEmpty())
	{
		Health.ProviderRouteDecision.SelectedTransportKind = TEXT("http");
	}
	if (Health.ProviderRouteDecision.SelectedServiceLaneId.IsEmpty())
	{
		Health.ProviderRouteDecision.SelectedServiceLaneId =
			ProviderDefaults.ProviderRouteDecision.SelectedServiceLaneId;
	}
	Health.ProviderRouteDecision.bSelectedCustomEndpointRoute =
		Health.ProviderProfileDefinition.bUserLabeled
		&& Health.ProviderProfileDefinition.bSupportsCustomBaseUrl
		&& !Health.ProviderProfileDefinition.EndpointBaseUrl.IsEmpty()
		&& !Health.ProviderProfileDefinition.EndpointBaseUrl.Contains(
			TEXT("127.0.0.1"),
			ESearchCase::IgnoreCase
		);
	if (Health.PayloadCustodyProfileId.IsEmpty())
	{
		Health.PayloadCustodyProfileId = TEXT("downloadable-model-payload-custody-v1");
	}
	if (!Health.PayloadCustodyProfileDefinition.IsStructurallyValid())
	{
		Health.PayloadCustodyProfileDefinition =
			UHyperTwistContractLibrary::MakeMockSpeechServiceHealth().PayloadCustodyProfileDefinition;
	}
	if (Health.SupportedModelPayloadIds.Num() <= 0)
	{
		Health.SupportedModelPayloadIds =
			UHyperTwistContractLibrary::MakeMockSpeechServiceHealth().SupportedModelPayloadIds;
	}
	if (Health.SupportedModelPayloads.Num() <= 0)
	{
		Health.SupportedModelPayloads =
			UHyperTwistContractLibrary::MakeMockSpeechServiceHealth().SupportedModelPayloads;
	}
	LastTransportError.Reset();
	Health.LastError.Reset();
	return Health;
}
