using System.Text.Json;
using System.Text.Json.Serialization;
using Lumi.Companion.Protocol;

namespace Lumi.Companion.App;

public sealed record DevelopmentBuildManifest(
    [property: JsonPropertyName("schema_version")] int SchemaVersion,
    [property: JsonPropertyName("mode")] string Mode,
    [property: JsonPropertyName("build_checksum")] string BuildChecksum,
    [property: JsonPropertyName("generated_at")] string GeneratedAt,
    [property: JsonPropertyName("components")] IReadOnlyDictionary<string, string> Components)
{
    public static DevelopmentBuildManifest? Load()
    {
        var path = Path.Combine(AppContext.BaseDirectory, ".lumi-dev-build.json");
        if (!File.Exists(path)) return null;
        try
        {
            var manifest = JsonSerializer.Deserialize<DevelopmentBuildManifest>(File.ReadAllText(path), ProtocolV1.JsonOptions);
            return manifest is { SchemaVersion: 1 } && IsSha256(manifest.BuildChecksum)
                ? manifest with { Components = Sanitize(manifest.Components) }
                : null;
        }
        catch { return null; }
    }

    private static IReadOnlyDictionary<string, string> Sanitize(IReadOnlyDictionary<string, string>? input)
    {
        if (input is null) return new Dictionary<string, string>();
        return input
            .Where(entry => entry.Key.Length is > 0 and <= 160 && IsSha256(entry.Value))
            .ToDictionary(entry => entry.Key, entry => entry.Value.ToLowerInvariant(), StringComparer.OrdinalIgnoreCase);
    }

    private static bool IsSha256(string? value) => value is { Length: 64 } && value.All(Uri.IsHexDigit);
}
