// PRE-GENERATED (design session). Downloads the official Equalizer APO installer and launches it.
// NOTE: APO install is NOT silent — it needs device selection + a REBOOT. So "auto install"
// = download official installer + launch it; the user completes the wizard and reboots.
// Untested here (needs network + admin). Verify the download URL in the dev session.
using System;
using System.Diagnostics;
using System.IO;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;

namespace DansoriEQ.App.Apo;

public static class ApoInstaller
{
    // SourceForge "latest" redirect for Equalizer APO. VERIFY current link in dev session.
    public const string DownloadUrl = "https://sourceforge.net/projects/equalizerapo/files/latest/download";

    public static async Task<string> DownloadAsync(IProgress<double>? progress = null, CancellationToken ct = default)
    {
        var target = Path.Combine(Path.GetTempPath(), "EqualizerAPO-setup.exe");

        using var http = new HttpClient();
        http.DefaultRequestHeaders.Add("User-Agent", "DansoriEQ");
        using var resp = await http.GetAsync(DownloadUrl, HttpCompletionOption.ResponseHeadersRead, ct);
        resp.EnsureSuccessStatusCode();

        var total = resp.Content.Headers.ContentLength ?? -1L;
        await using var src = await resp.Content.ReadAsStreamAsync(ct);
        await using var dst = File.Create(target);

        var buffer = new byte[81920];
        long readTotal = 0;
        int n;
        while ((n = await src.ReadAsync(buffer, ct)) > 0)
        {
            await dst.WriteAsync(buffer.AsMemory(0, n), ct);
            readTotal += n;
            if (total > 0) progress?.Report((double)readTotal / total);
        }
        return target;
    }

    public static void Launch(string installerPath)
        => Process.Start(new ProcessStartInfo(installerPath) { UseShellExecute = true });   // triggers UAC
}
