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

namespace NeonSprawl.Server.Game.Mastery;

/// <summary>DI registration for the fail-fast mastery catalog (NEO-46).</summary>
public static class MasteryCatalogServiceCollectionExtensions
{
    /// <summary>Binds <see cref="ContentPathsOptions"/> and registers <see cref="MasteryCatalog"/> and <see cref="IMasteryCatalogRegistry"/> as singletons.</summary>
    public static IServiceCollection AddMasteryCatalog(this IServiceCollection services, IConfiguration configuration)
    {
        services.AddOptions<ContentPathsOptions>()
            .Bind(configuration.GetSection(ContentPathsOptions.SectionName));

        services.AddSingleton<MasteryCatalog>(sp =>
        {
            var hostEnv = sp.GetRequiredService<IHostEnvironment>();
            var opts = sp.GetRequiredService<IOptions<ContentPathsOptions>>().Value;
            var skillCatalog = sp.GetRequiredService<SkillDefinitionCatalog>();
            var logger = sp.GetRequiredService<ILoggerFactory>()
                .CreateLogger("NeonSprawl.Server.Game.Mastery.MasteryCatalog");

            var masteryDir = MasteryCatalogPathResolution.ResolveMasteryDirectory(
                opts.MasteryDirectory,
                hostEnv.ContentRootPath);
            var schemaPath = MasteryCatalogPathResolution.ResolveMasteryCatalogSchemaPath(
                masteryDir,
                opts.MasteryCatalogSchemaPath,
                hostEnv.ContentRootPath);

            var knownSkillIds = skillCatalog.ById.Keys.ToHashSet(StringComparer.Ordinal);
            return MasteryCatalogLoader.Load(masteryDir, schemaPath, knownSkillIds, logger);
        });

        services.AddSingleton<IMasteryCatalogRegistry>(sp =>
            new MasteryCatalogRegistry(sp.GetRequiredService<MasteryCatalog>()));

        return services;
    }
}
