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

namespace NeonSprawl.Server.Game.Combat;

/// <summary>DI registration for the fail-fast ability catalog (NEO-77).</summary>
public static class AbilityCatalogServiceCollectionExtensions
{
    /// <summary>Binds <see cref="ContentPathsOptions"/> and registers <see cref="AbilityDefinitionCatalog"/> as a singleton.</summary>
    public static IServiceCollection AddAbilityDefinitionCatalog(this IServiceCollection services, IConfiguration configuration)
    {
        services.AddOptions<ContentPathsOptions>()
            .Bind(configuration.GetSection(ContentPathsOptions.SectionName));

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

            var abilitiesDir = AbilityCatalogPathResolution.ResolveAbilitiesDirectory(
                opts.AbilitiesDirectory,
                hostEnv.ContentRootPath);
            var schemaPath = AbilityCatalogPathResolution.ResolveAbilityDefSchemaPath(
                abilitiesDir,
                opts.AbilityDefSchemaPath,
                hostEnv.ContentRootPath);

            return AbilityDefinitionCatalogLoader.Load(abilitiesDir, schemaPath, logger);
        });

        return services;
    }
}
