using BrassAndSigil.Server.Commands;
using Spectre.Console;
using Spectre.Console.Cli;

// Detect interactive double-click on Windows so we can hold the console open at exit
// (otherwise the window vanishes before the user can read errors).
var interactive = !Console.IsInputRedirected && OperatingSystem.IsWindows();

var app = new CommandApp<RunCommand>();
app.Configure(config =>
{
    config.SetApplicationName("brass-sigil-server");
    config.SetApplicationVersion("0.1.0");

    config.AddCommand<InstallCommand>("install")
        .WithDescription("Force a fresh setup: download mods + run the NeoForge installer.");

    config.AddCommand<SyncCommand>("sync")
        .WithDescription("Update mods to match the current manifest. Server should be stopped first.");

    config.AddCommand<RunCommand>("run")
        .WithDescription("Run the server daemon (auto-installs anything missing, then serves the web UI).")
        .WithAlias("start");

    config.AddCommand<CheckCommand>("check")
        .WithDescription("Verify install: dependencies, EULA, manifest reachability.");

    config.AddCommand<SetPasswordCommand>("set-password")
        .WithDescription("Set or rotate the web panel admin password.");
});

int result;
try
{
    result = await app.RunAsync(args);
}
catch (Exception ex)
{
    AnsiConsole.WriteException(ex, ExceptionFormats.ShortenEverything);
    result = 1;
}

// Hold the console open at exit only when an error occurred during interactive use.
// Successful daemon termination (Ctrl+C, /api/server/stop) closes cleanly.
if (interactive && result != 0)
{
    AnsiConsole.MarkupLine("");
    AnsiConsole.MarkupLine("[grey]Press any key to close...[/]");
    Console.ReadKey(intercept: true);
}

return result;
