using NeonSprawl.Server.Game.PositionState;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Options;

namespace NeonSprawl.Server.Game.Skills;

/// <summary>Registers skill XP persistence: PostgreSQL when configured, otherwise in-memory fallback (NEO-38).</summary>
public static class SkillProgressionServiceCollectionExtensions
{
    public static IServiceCollection AddSkillProgressionStore(this IServiceCollection services, IConfiguration configuration)
    {
        services.AddOptions<ContentPathsOptions>()
            .Bind(configuration.GetSection(ContentPathsOptions.SectionName));

        var cs = configuration.GetConnectionString(PositionStateServiceCollectionExtensions.NeonSprawlConnectionStringName);
        if (!string.IsNullOrWhiteSpace(cs))
        {
            services.AddSingleton<IPlayerSkillProgressionStore, PostgresPlayerSkillProgressionStore>();
        }
        else
        {
            services.AddSingleton<IPlayerSkillProgressionStore, InMemoryPlayerSkillProgressionStore>();
        }

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

            var skillsDir = SkillCatalogPathResolution.ResolveSkillsDirectory(opts.SkillsDirectory, hostEnv.ContentRootPath);
            var curvePath = Path.Combine(skillsDir, "prototype_level_curve.json");
            var schemaPath = Path.GetFullPath(Path.Combine(skillsDir, "..", "schemas", "level-curve.schema.json"));
            return ContentBackedSkillLevelCurve.Load(skillsDir, curvePath, schemaPath, logger);
        });

        return services;
    }
}
