namespace SirayaPrinter.Sync;

internal static class Program
{
    private static int Main(string[] args)
    {
        try
        {
            return RunAsync(args).GetAwaiter().GetResult();
        }
        catch (Exception ex)
        {
            Console.Error.WriteLine($"ERROR: {ex.Message}");
            return 1;
        }
    }

    private static async Task<int> RunAsync(string[] args)
    {
        if (args.Length == 0 || args[0] is "-h" or "--help" or "help")
        {
            PrintHelp();
            return 0;
        }

        var channel = "dev";
        var openBrowser = false;
        var command = args[0].ToLowerInvariant();

        for (var i = 1; i < args.Length; i++)
        {
            if (args[i] == "--channel" && i + 1 < args.Length)
            {
                channel = args[++i];
            }
            else if (args[i] == "--open")
            {
                openBrowser = true;
            }
        }

        if (command == "apply")
            openBrowser = true;

        var engine = new SyncEngine();
        using var cts = new CancellationTokenSource(TimeSpan.FromMinutes(15));

        switch (command)
        {
            case "check":
                await engine.CheckAsync(channel, cts.Token);
                return 0;
            case "apply":
                await engine.ApplyAsync(channel, openBrowser, cts.Token);
                return 0;
            default:
                Console.Error.WriteLine($"Unknown command: {command}");
                PrintHelp();
                return 2;
        }
    }

    private static void PrintHelp()
    {
        Console.WriteLine("Siraya Printer Sync — OTA update for Windows register PCs");
        Console.WriteLine();
        Console.WriteLine("Usage:");
        Console.WriteLine("  Sync.exe check  [--channel dev|stable]");
        Console.WriteLine("  Sync.exe apply  [--channel dev|stable] [--open]");
        Console.WriteLine();
        Console.WriteLine("  dev     — latest upload (default, for testing)");
        Console.WriteLine("  stable  — semver releases");
    }
}
