using System.Collections.Immutable;
using System.Linq;
using Microsoft.CodeAnalysis;
using NodePipeline.Engine.CodeGeneration.Abstractions;

namespace NodePipeline.Engine.CodeGeneration;

[Generator]
public class NodePipelineCoreClassesGenerator : IIncrementalGenerator
{
    public void Initialize(IncrementalGeneratorInitializationContext context)
    {
        var nodeSymbols = NodeGeneratorHelper.GetNodeSymbols(context);

        context.RegisterSourceOutput(nodeSymbols, (spc, symbols) =>
        {
            var nodes = symbols.Where(s => s is not null)
                .ToImmutableArray();
            var (model, diagnostics) = NodeModelBuilder.Build(nodes);

            diagnostics.ForEach(spc.ReportDiagnostic);
            if (diagnostics.Any(q => q.Severity > DiagnosticSeverity.Warning)) return;

            var factorySource = NodeFactoryGenerator.Generate(model);
            spc.AddSource("GeneratedNodeFactory.g.cs", factorySource);

            var validatorSource = NodeValidatorGenerator.Generate(model);
            spc.AddSource("GeneratedNodeValidator.g.cs", validatorSource);
        });
    }
}