using System.CommandLine;

public static class ReplayCommand
{
    public static Command Create()
    {
        var fileArg = new Argument<FileInfo>("scenario-file");
        var speedOpt = new Option<double>("--speed", () => 60, "Speed multiplier (0=instant, 1=realtime)");
        var baseUrlOpt = new Option<string>("--base-url", () => "http://localhost:5270");
        var pollOpt = new Option<bool>("--poll", () => false, "Poll alerts/scores after each cluster");
        var pollIntervalOpt = new Option<int>("--poll-interval", () => 5, "Seconds between polls");
        var usernameOpt = new Option<string>("--username", () => "physician.demo", "API login username");
        var passwordOpt = new Option<string>("--password", () => "DemoPhysician1!", "API login password");

        var command = new Command("replay", "Replay a scenario against the API")
        {
            fileArg, speedOpt, baseUrlOpt, pollOpt, pollIntervalOpt, usernameOpt, passwordOpt
        };

        command.SetHandler(async (FileInfo file, double speed, string baseUrl, bool poll, int pollInterval,
            string username, string password) =>
        {
            var scenario = ScenarioLoader.Load(file.FullName);
            var errors = ScenarioValidator.Validate(scenario);
            if (errors.Count > 0)
            {
                SimulatorConsole.Error($"Scenario validation failed with {errors.Count} error(s):");
                foreach (var err in errors) SimulatorConsole.Error($"  • {err}");
                return;
            }

            using var http = new HttpClient { BaseAddress = new Uri(baseUrl) };
            var client = new VigilCareApiClient(http);

            SimulatorConsole.Info($"Authenticating as {username}...");
            await client.LoginAsync(username, password);
            SimulatorConsole.Info("Authenticated.");

            var poller = poll ? new ApiPoller(client) : null;
            var engine = new ReplayEngine(client, poller);
            var options = new ReplayOptions(speed, poll, pollInterval);

            await engine.RunAsync(scenario, options);
        }, fileArg, speedOpt, baseUrlOpt, pollOpt, pollIntervalOpt, usernameOpt, passwordOpt);

        return command;
    }
}