using System.Collections.Generic;
using System.Text;

namespace AyCode.Core.Serializers.SourceGenerator;

/// <summary>
/// Module-init emit pass: generates the static class with a <c>[ModuleInitializer]</c> method that
/// auto-registers every generated writer / reader instance into the runtime registries
/// (<c>AcBinarySerializer.RegisterGeneratedWriter</c> / <c>AcBinaryDeserializer.RegisterGeneratedReader</c>).
/// Emitted once per compilation as <c>AcBinaryGeneratedWriters_Init.g.cs</c>.
/// </summary>
public partial class AcBinarySourceGenerator
{
    private static string GenInit(List<SerializableClassInfo> classes)
    {
        var sb = new StringBuilder(512);
        sb.AppendLine("// <auto-generated/>");
        sb.AppendLine("using System.Runtime.CompilerServices;");
        sb.AppendLine("using AyCode.Core.Serializers.Binaries;");
        sb.AppendLine();
        sb.AppendLine("namespace AyCode.Core.Serializers.Generated;");
        sb.AppendLine();
        sb.AppendLine("internal static class AcBinaryGeneratedWritersInit");
        sb.AppendLine("{");
        sb.AppendLine("    [ModuleInitializer]");
        sb.AppendLine("    internal static void Register()");
        sb.AppendLine("    {");
        foreach (var ci in classes)
        {
            var writerRef = string.IsNullOrEmpty(ci.Namespace)
                ? $"{ci.ClassName}_GeneratedWriter"
                : $"{ci.Namespace}.{ci.ClassName}_GeneratedWriter";
            var readerRef = string.IsNullOrEmpty(ci.Namespace)
                ? $"{ci.ClassName}_GeneratedReader"
                : $"{ci.Namespace}.{ci.ClassName}_GeneratedReader";
            sb.AppendLine($"        AcBinarySerializer.RegisterGeneratedWriter(typeof({ci.FullTypeName}), {writerRef}.Instance);");
            sb.AppendLine($"        AcBinaryDeserializer.RegisterGeneratedReader(typeof({ci.FullTypeName}), {readerRef}.Instance);");
        }
        sb.AppendLine("    }");
        sb.AppendLine("}");
        return sb.ToString();
    }
}
