using System.Collections.Generic;
using System.Text;
using Motus.Codegen.Model;

namespace Motus.Codegen.Emit;

/// <summary>
/// Emits the MotusPluginRegistry source with a module initializer
/// that registers discovered plugins with the PluginDiscovery bridge.
/// </summary>
internal static class PluginRegistryEmitter
{
    internal static string Emit(IReadOnlyList<PluginTypeInfo> plugins)
    {
        var sb = new StringBuilder();
        sb.AppendLine("// <auto-generated/>");
        sb.AppendLine("#nullable enable");
        sb.AppendLine("using System.Runtime.CompilerServices;");
        sb.AppendLine("using Motus.Abstractions;");
        sb.AppendLine();
        sb.AppendLine("namespace Motus.Generated;");
        sb.AppendLine();
        sb.AppendLine("internal static class MotusPluginRegistry");
        sb.AppendLine("{");
        sb.AppendLine("    [ModuleInitializer]");
        sb.AppendLine("    internal static void Register()");
        sb.AppendLine("    {");
        sb.AppendLine("        PluginDiscovery.Factory = static () =>");

        if (plugins.Count == 0)
        {
            sb.AppendLine("            System.Array.Empty<IPlugin>();");
        }
        else
        {
            sb.AppendLine("            new IPlugin[]");
            sb.AppendLine("            {");
            foreach (var plugin in plugins)
            {
                sb.AppendLine($"                new global::{plugin.FullyQualifiedName}(),");
            }
            sb.AppendLine("            };");
        }

        sb.AppendLine("    }");
        sb.AppendLine("}");

        return sb.ToString();
    }
}
