#pragma once

#include "CoreMinimal.h"
#include "WingServer.h"
#include "WingHandler.h"
#include "WingFetcher.h"
#include "WingProperty.h"
#include "WingUtils.h"
#include "WingTypes.h"
#include "Details_Dump.generated.h"

UCLASS()
class UWing_Details_Dump : public UWingHandler
{
	GENERATED_BODY()

public:
	UPROPERTY(EditAnywhere, meta=(Description="Target object"))
	FString Object;

	UPROPERTY(meta=(Optional, Description="Substring filter for property names"))
	FString Query;

	virtual void Register() override
	{
		UWingServer::AddHandler(this,
			TEXT("Test handler: dump properties using FWingProperty."));
	}

	virtual void Handle() override
	{
		WingFetcher F;
		UObject* Target = F.Walk(Object).Cast<UObject>();
		if (!Target) return;

		TArray<FWingProperty> Props = FWingProperty::GetDetailsImmutable(Target, CPF_Edit);
		Props = FWingProperty::FindAllSubstring(Props, Query);

		// Group by category, preserving within-category order.
		TSortedMap<FString, TArray<FWingProperty>> Categories;
		for (const FWingProperty& P : Props)
		{
			FString Category = P.Prop->GetMetaData(TEXT("Category"));
			if (Category.IsEmpty()) Category = TEXT("Unclassified");
			Categories.FindOrAdd(Category).Add(P);
		}

		FStringBuilderBase& Out = UWingServer::GetPrintBuffer();
		for (const auto& Pair : Categories)
		{
			Out.Appendf(TEXT("\n%s:\n"), *Pair.Key);
			for (const FWingProperty& P : Pair.Value)
			{
				bool bEditable = !P->HasAnyPropertyFlags(CPF_EditConst);
				Out.Appendf(TEXT("    %s %s %s = %s\n"),
					bEditable ? TEXT("editable") : TEXT("readonly"),
					*UWingTypes::TypeToText(P.Prop),
					*WingUtils::FormatName(P.Prop),
					*P.GetTruncatedText(100));
			}
		}
	}
};
