using System.Text.Json;
using System.Text.Json.Serialization;

namespace SirayaPrinter.Sync;

public sealed class SyncManifest
{
    [JsonPropertyName("version")]
    public string Version { get; set; } = "";

    [JsonPropertyName("channel")]
    public string Channel { get; set; } = "";

    [JsonPropertyName("releasedAt")]
    public string? ReleasedAt { get; set; }

    [JsonPropertyName("baseUrl")]
    public string BaseUrl { get; set; } = "";

    [JsonPropertyName("files")]
    public List<ManifestFile> Files { get; set; } = new();
}

public sealed class ManifestFile
{
    [JsonPropertyName("path")]
    public string Path { get; set; } = "";

    [JsonPropertyName("sha256")]
    public string Sha256 { get; set; } = "";

    [JsonPropertyName("size")]
    public long Size { get; set; }
}

public static class ManifestLoader
{
    private static readonly JsonSerializerOptions JsonOptions = new()
    {
        PropertyNameCaseInsensitive = true,
    };

    public static async Task<SyncManifest> FetchAsync(HttpClient http, string manifestUrl, CancellationToken ct)
    {
        var json = await http.GetStringAsync(manifestUrl, ct);
        var manifest = JsonSerializer.Deserialize<SyncManifest>(json, JsonOptions)
            ?? throw new InvalidOperationException("Invalid manifest JSON");
        if (string.IsNullOrWhiteSpace(manifest.BaseUrl))
            throw new InvalidOperationException("Manifest missing baseUrl");
        if (manifest.Files.Count == 0)
            throw new InvalidOperationException("Manifest has no files");
        return manifest;
    }
}
