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

namespace NexusIdentity.Api.Services;

public sealed class DownloadManifestService
{
    private readonly HttpClient _httpClient;
    private readonly IConfiguration _configuration;
    private readonly ILogger<DownloadManifestService> _logger;

    public DownloadManifestService(HttpClient httpClient, IConfiguration configuration, ILogger<DownloadManifestService> logger)
    {
        _httpClient = httpClient;
        _configuration = configuration;
        _logger = logger;
    }

    public async Task<JsonDocument?> GetLatestManifestAsync(CancellationToken ct)
    {
        var localRoot = Environment.GetEnvironmentVariable("NEXUS_DOWNLOADS_ROOT");
        if (!string.IsNullOrWhiteSpace(localRoot))
        {
            var localPath = Path.Combine(localRoot, "latest.json");
            if (File.Exists(localPath))
            {
                await using var stream = File.OpenRead(localPath);
                return await JsonDocument.ParseAsync(stream, cancellationToken: ct);
            }
        }

        var baseUrl = _configuration["Nexus:DownloadsBaseUrl"]
            ?? "https://nexus.ninjakernen.info/downloads";

        try
        {
            var bytes = await _httpClient.GetByteArrayAsync($"{baseUrl.TrimEnd('/')}/latest.json", ct);
            var text = Encoding.UTF8.GetString(bytes);
            if (bytes.Length >= 3 && bytes[0] == 0xEF && bytes[1] == 0xBB && bytes[2] == 0xBF)
            {
                text = Encoding.UTF8.GetString(bytes, 3, bytes.Length - 3);
            }

            return JsonDocument.Parse(text);
        }
        catch (Exception ex)
        {
            _logger.LogWarning(ex, "Failed to load download manifest from {BaseUrl}", baseUrl);
            return null;
        }
    }
}
