// Program.cs  –  AttrInspector v3
// Requires SDK-style project (.NET 8+) and
// <PackageReference Include="System.Reflection.MetadataLoadContext" Version="9.0.5" />

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.Loader;
using System.Text;

internal static class AttrInspector
{
    public static void Main(string[] args)
    {
        if (args.Length == 0)
        {
            Console.Error.WriteLine("Usage: AttrInspector <target-dll> [csv-output]");
            return;
        }

        var targetDll   = Path.GetFullPath(args[0]);
        var csvPath     = args.Length > 1
                            ? Path.GetFullPath(args[1])
                            : Path.Combine(AppContext.BaseDirectory, "foema_attributes.csv");

        if (!File.Exists(targetDll))
        {
            Console.Error.WriteLine($"DLL not found: {targetDll}");
            return;
        }

        // ---------- assembly loading with dependency resolver ----------
        var resolver   = new AssemblyDependencyResolver(targetDll);
        var probingDir = Path.GetDirectoryName(targetDll)!;
        var alc        = new AssemblyLoadContext("scan", isCollectible: true);

        alc.Resolving += (_, name) =>
        {
            var path = resolver.ResolveAssemblyToPath(name) ??
                       Path.Combine(probingDir, $"{name.Name}.dll");
            return File.Exists(path) ? alc.LoadFromAssemblyPath(path) : null;
        };

        var asm = alc.LoadFromAssemblyPath(targetDll);

        Type[] types;
        try { types = asm.GetTypes(); }
        catch (ReflectionTypeLoadException ex)
        {
            types = ex.Types.Where(t => t is not null).ToArray()!;
            Console.Error.WriteLine($"[WARN] {ex.LoaderExceptions!.Length} referenced types could not be loaded and were skipped.");
        }

        var rows = new List<(string Source, string Entity, string Attr)>();

        // ---- 1) literals inside *.AttrNames ----
        foreach (var ent in types)
        {
            var attrNames = ent.GetNestedTypes(BindingFlags.Public | BindingFlags.NonPublic)
                               .FirstOrDefault(nt => nt.Name == "AttrNames");
            if (attrNames == null) continue;

            foreach (var f in attrNames.GetFields(BindingFlags.Public | BindingFlags.Static))
            {
                if (!(f.IsLiteral && f.FieldType == typeof(string))) continue;

                var lit = (string)f.GetRawConstantValue()!;
                if (!lit.StartsWith("foema_", StringComparison.OrdinalIgnoreCase)) continue;

                rows.Add((Source: ent.Name, Entity: ent.Name, Attr: lit));
            }
        }

        // ---- 2) static-readonly arrays called *Attributes ----
        foreach (var t in types)
        {
            foreach (var f in t.GetFields(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static))
            {
                if (!(f.FieldType == typeof(string[]) &&
                      f.Name.EndsWith("Attributes", StringComparison.OrdinalIgnoreCase)))
                    continue;

                if (f.GetValue(null) is not string[] values) continue;

                // entity derived from first segment before '.'
                var entity = t.Name.Replace("Repository", string.Empty, StringComparison.OrdinalIgnoreCase);

                foreach (var val in values.Where(v => v.StartsWith("foema_", StringComparison.OrdinalIgnoreCase)))
                    rows.Add((Source: t.Name, Entity: entity, Attr: val));
            }
        }

        // ---- 3) de-duplicate ----
        var distinct = rows.Distinct();

        // ---- 4) write CSV ----
        Directory.CreateDirectory(Path.GetDirectoryName(csvPath)!);

        using var sw = new StreamWriter(csvPath, false, Encoding.UTF8);
        sw.WriteLine("source,entity,attribute");

        foreach (var r in distinct.OrderBy(r => r.Source).ThenBy(r => r.Attr))
            sw.WriteLine($"{Csv(r.Source)},{Csv(r.Entity)},{Csv(r.Attr)}");

        Console.WriteLine($"✓ Wrote {distinct.Count()} rows to {csvPath}");
        alc.Unload();
    }

    private static string Csv(string s)
    {
        // naive escape: enclose in quotes if needed and double any embedded quotes
        return s.Contains(',') || s.Contains('"')
            ? $"\"{s.Replace("\"", "\"\"")}\""
            : s;
    }
}
explain on a non technical level what this code does, an how reliable the results are: