// Copyright ExByte Studios. Item Interaction Ecosystem.

#include "ItemDebugSubsystem.h"
#include "InteractionTraceComponent.h"
#include "InteractionResolver.h"
#include "InteractionTypes.h"
#include "HeldItemComponent.h"
#include "GameFramework/Pawn.h"
#include "GameFramework/PlayerController.h"
#include "Engine/Engine.h"

static TAutoConsoleVariable<int32> CVarItemDebugHUD(
	TEXT("ItemEco.DebugHUD"), 0,
	TEXT("Draw the Item Ecosystem on-screen debugger (held item / target / interactions)."),
	ECVF_Cheat);

void UItemDebugSubsystem::Tick(float DeltaTime)
{
	Super::Tick(DeltaTime);
	if (CVarItemDebugHUD.GetValueOnGameThread() <= 0 || !GEngine)
	{
		return;
	}

	UWorld* World = GetWorld();
	APlayerController* PC = World ? World->GetFirstPlayerController() : nullptr;
	APawn* Pawn = PC ? PC->GetPawn() : nullptr;
	if (!Pawn)
	{
		return;
	}

	int32 Key = 9000;
	auto Line = [&Key](const FString& Text, const FColor Color = FColor::White)
	{
		GEngine->AddOnScreenDebugMessage(Key++, 0.f, Color, Text);
	};

	Line(TEXT("== Item Ecosystem Debug =="), FColor::Cyan);

	if (const UHeldItemComponent* Held = Pawn->FindComponentByClass<UHeldItemComponent>())
	{
		FItemInstanceData HeldItem;
		if (Held->GetHeldItem(HeldItem))
		{
			Line(FString::Printf(TEXT("Held: %s"), *HeldItem.ItemId.ToString()), FColor::Yellow);
		}
		else
		{
			Line(TEXT("Held: -"));
		}
	}

	AActor* Target = nullptr;
	if (const UInteractionTraceComponent* Trace = Pawn->FindComponentByClass<UInteractionTraceComponent>())
	{
		Target = Trace->CurrentTarget;
	}
	Line(FString::Printf(TEXT("Target: %s"), *GetNameSafe(Target)), FColor::Green);

	if (Target)
	{
		TArray<FInteractionOption> Options;
		UInteractionResolver::GetAvailableInteractions(Pawn, Target, Options);
		for (const FInteractionOption& Opt : Options)
		{
			Line(FString::Printf(TEXT("  [%d] %s%s"),
				Opt.Priority, *Opt.DisplayText.ToString(),
				Opt.bIsEnabled ? TEXT("") : TEXT(" (disabled)")),
				Opt.bIsEnabled ? FColor::White : FColor::Silver);
		}
	}
}

TStatId UItemDebugSubsystem::GetStatId() const
{
	RETURN_QUICK_DECLARE_CYCLE_STAT(UItemDebugSubsystem, STATGROUP_Tickables);
}

bool UItemDebugSubsystem::DoesSupportWorldType(const EWorldType::Type WorldType) const
{
	return WorldType == EWorldType::Game || WorldType == EWorldType::PIE;
}
