using BrassAndSigil.Server.Models;
using BrassAndSigil.Server.Services;
using Spectre.Console;
using Spectre.Console.Cli;

namespace BrassAndSigil.Server.Commands;

public sealed class SyncCommand : AsyncCommand<BaseCommandSettings>
{
    public override async Task<int> ExecuteAsync(CommandContext context, BaseCommandSettings settings)
    {
        var config = ServerConfig.Load(settings.ConfigPath);
        AnsiConsole.MarkupLine($"[bold]Syncing[/] from [blue]{config.ManifestUrl}[/]");
        AnsiConsole.MarkupLine($"[grey]Target: {Path.GetFullPath(config.ServerDir)}[/]");
        AnsiConsole.MarkupLine("");

        var sync = new ManifestSync();
        var progress = new Progress<string>(msg => AnsiConsole.MarkupLine($"  [grey]{msg.EscapeMarkup()}[/]"));
        try
        {
            var result = await sync.SyncAsync(config.ManifestUrl, config.ServerDir, progress);
            AnsiConsole.MarkupLine("");
            AnsiConsole.MarkupLine($"[green]✓[/] pack v{result.PackVersion} | downloaded={result.Downloaded} removed={result.Removed} client-only-skipped={result.Skipped}");
            return 0;
        }
        catch (Exception ex)
        {
            AnsiConsole.MarkupLine($"[red]✗[/] {ex.Message.EscapeMarkup()}");
            return 1;
        }
    }
}
