using System.Text.Json;
namespace SilverOS.Welcome.Core.Flavours;

public sealed class FlavourValidationException(string message) : Exception(message);

public sealed class FlavourLoader : IFlavourLoader
{
    public IReadOnlyList<FlavourManifest> Load(string directory)
    {
        var list = new List<FlavourManifest>();
        foreach (var file in Directory.EnumerateFiles(directory, "*.json").OrderBy(f => f))
        {
            FlavourManifest m;
            try { m = JsonSerializer.Deserialize<FlavourManifest>(File.ReadAllText(file), FlavourManifest.JsonOptions)
                      ?? throw new FlavourValidationException($"{Path.GetFileName(file)}: empty"); }
            catch (JsonException ex) { throw new FlavourValidationException($"{Path.GetFileName(file)}: {ex.Message}"); }
            if (string.IsNullOrWhiteSpace(m.Id)) throw new FlavourValidationException($"{Path.GetFileName(file)}: missing id");
            if (m.Hardening.Modules.Count == 0) throw new FlavourValidationException($"{Path.GetFileName(file)}: no hardening modules");
            list.Add(m);
        }
        if (list.Count == 0) throw new FlavourValidationException("no flavour manifests found");
        if (list.Count(m => m.IsDefault) != 1) throw new FlavourValidationException("exactly one flavour must be isDefault");
        return list.OrderByDescending(m => m.IsDefault).ThenBy(m => m.Label).ToList();
    }
}
