using System.CommandLine;
using VigilCare.Simulation;

public static class ReplayAllCommand
{
    public static Command Create()
    {
        var dirArg = new Argument<DirectoryInfo>("directory", "Directory containing scenario JSON files");
        var speedOpt = new Option<double>("--speed", () => 60);
        var baseUrlOpt = new Option<string>("--base-url", () => "http://localhost:5270");
        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-all", "Replay all scenarios in a directory")
        {
            dirArg, speedOpt, baseUrlOpt, usernameOpt, passwordOpt
        };

        command.SetHandler(async (DirectoryInfo dir, double speed, string baseUrl,
            string username, string password) =>
        {
            var files = dir.GetFiles("*.json")
                .Where(f => f.Name != "schema.json")
                .OrderBy(f => f.Name)
                .ToList();

            if (files.Count == 0)
            {
                SimulatorConsole.Warn($"No .json scenario files found in {dir.FullName}");
                return;
            }

            SimulatorConsole.Header($"Replaying {files.Count} scenarios from {dir.Name}");

            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 engine = new ReplayEngine(client, poller: null, new ConsoleReplayObserver());
            var results = new List<ReplayResult>();

            foreach (var file in files)
            {
                SimulatorConsole.Divider();
                var scenario = ScenarioLoader.Load(file.FullName);
                var errors = ScenarioValidator.Validate(scenario);
                if (errors.Count > 0)
                {
                    SimulatorConsole.Error($"Skipping {file.Name}: {errors.Count} validation error(s)");
                    continue;
                }

                var result = await engine.RunAsync(scenario, new ReplayOptions(speed));
                results.Add(result);
            }

            SimulatorConsole.BatchSummary(results);
        }, dirArg, speedOpt, baseUrlOpt, usernameOpt, passwordOpt);

        return command;
    }
}