#pragma once

#include "CoreMinimal.h"
#include "WingServer.h"
#include "WingBasics.h"
#include "WingUtils.h"
#include "AssetRegistry/AssetData.h"
#include "AssetRegistry/IAssetRegistry.h"
#include "Asset_FindReferences.generated.h"


// ---------------------------------------------------------------------------
// ---------------------------------------------------------------------------
// ---------------------------------------------------------------------------

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

public:
	UPROPERTY(EditAnywhere, meta=(Description="Asset to find references for"))
	FString Asset;

	virtual void Register() override
	{
		UWingServer::AddHandler(this,
			TEXT("Find all assets that reference a given asset."));
	}
	virtual void Handle() override
	{
		IAssetRegistry& Registry = *IAssetRegistry::Get();

		// Verify the asset exists
		FAssetData AssetData = Registry.GetAssetByObjectPath(FSoftObjectPath(Asset));
		if (!AssetData.IsValid())
		{
			WingOut::Stdout.Printf(TEXT("ERROR: Asset not found: %s\n"), *Asset);
			return;
		}

		TArray<FName> Referencers;
		Registry.GetReferencers(FName(*Asset), Referencers);

		if (Referencers.Num() == 0)
		{
			WingOut::Stdout.Print(TEXT("No referencers found.\n"));
			return;
		}

		// Classify referencers by looking up their asset class
		for (const FName& Ref : Referencers)
		{
			FString RefStr = Ref.ToString();
			TArray<FAssetData> RefAssets;
			Registry.GetAssetsByPackageName(Ref, RefAssets);
			if (RefAssets.Num() > 0)
			{
				WingOut::Stdout.Printf(TEXT("%s %s\n"),
					*WingUtils::FormatName(RefAssets[0].GetClass()),
					*RefStr);
			}
			else
			{
				WingOut::Stdout.Printf(TEXT("Unknown %s\n"), *RefStr);
			}
		}
	}
};
