using CUE4Parse.UE4.Assets.Exports;
using CUE4Parse.UE4.Assets.Objects;
using System.Reflection;

public static class StructMapper
{
    private static readonly MethodInfo _getOrDefaultMethod = typeof(AbstractPropertyHolder)
        .GetMethods()
        .First(m => m.Name == "GetOrDefault" && m.GetGenericArguments().Length == 1);

    public static T MapToStruct<T>(this FStructFallback fallback) where T : struct
    {
        object result = new T();
        var fields = typeof(T).GetFields(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance);

        foreach (var field in fields)
        {
            try
            {
                var genericMethod = _getOrDefaultMethod.MakeGenericMethod(field.FieldType);
                var value = genericMethod.Invoke(fallback, new object[] { field.Name, null!, StringComparison.Ordinal });

                if (value != null)
                    field.SetValue(result, value);
            }
            catch (Exception ex)
            {
                Console.WriteLine($"Mapping failed for {field.Name}: {ex.InnerException?.Message ?? ex.Message}");
            }
        }

        return (T)result;
    }
}