using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Options;
using NeonSprawl.Server.Game.Skills;

namespace NeonSprawl.Server.Game.Npc;

/// <summary>DI registration for the fail-fast NPC behavior catalog (NEO-88).</summary>
public static class NpcBehaviorCatalogServiceCollectionExtensions
{
    /// <summary>Binds <see cref="ContentPathsOptions"/> and registers <see cref="NpcBehaviorDefinitionCatalog"/> as a singleton.</summary>
    public static IServiceCollection AddNpcBehaviorDefinitionCatalog(this IServiceCollection services, IConfiguration configuration)
    {
        services.AddOptions<ContentPathsOptions>()
            .Bind(configuration.GetSection(ContentPathsOptions.SectionName));

        services.AddSingleton<NpcBehaviorDefinitionCatalog>(sp =>
        {
            var hostEnv = sp.GetRequiredService<IHostEnvironment>();
            var opts = sp.GetRequiredService<IOptions<ContentPathsOptions>>().Value;
            var logger = sp.GetRequiredService<ILoggerFactory>()
                .CreateLogger("NeonSprawl.Server.Game.Npc.NpcBehaviorCatalog");

            var npcBehaviorsDir = NpcBehaviorCatalogPathResolution.ResolveNpcBehaviorsDirectory(
                opts.NpcBehaviorsDirectory,
                hostEnv.ContentRootPath);
            var schemaPath = NpcBehaviorCatalogPathResolution.ResolveNpcBehaviorDefSchemaPath(
                npcBehaviorsDir,
                opts.NpcBehaviorDefSchemaPath,
                hostEnv.ContentRootPath);

            return NpcBehaviorDefinitionCatalogLoader.Load(npcBehaviorsDir, schemaPath, logger);
        });

        return services;
    }
}
