using System.IO;
using System.Reflection;
using System.Threading;
using Json.Schema;

namespace StellaOps.Feedser.Source.Kev.Internal;

internal static class KevSchemaProvider
{
    private const string ResourceName = "StellaOps.Feedser.Source.Kev.Schemas.kev-catalog.schema.json";

    private static readonly Lazy<JsonSchema> CachedSchema = new(LoadSchema, LazyThreadSafetyMode.ExecutionAndPublication);

    public static JsonSchema Schema => CachedSchema.Value;

    private static JsonSchema LoadSchema()
    {
        var assembly = typeof(KevSchemaProvider).GetTypeInfo().Assembly;
        using var stream = assembly.GetManifestResourceStream(ResourceName)
            ?? throw new InvalidOperationException($"Embedded schema '{ResourceName}' was not found.");
        using var reader = new StreamReader(stream);
        var schemaJson = reader.ReadToEnd();
        return JsonSchema.FromText(schemaJson);
    }
}
