using System.Text.Json;
using ZB.MOM.WW.ScadaBridge.LoadHarness;

// Target-scale load harness (Phase-8 WP-4 / deferred-work register #25 + row 50).
//
// Full-scale protocol run (the WP-4 numbers):
//   dotnet run -c Release --project tests/ZB.MOM.WW.ScadaBridge.LoadHarness -- \
//     --sustain-minutes 20 --results loadharness-results.json
//
// Full 1-hour version, unchanged in every other respect:
//   ... -- --sustain-minutes 60 --results loadharness-results-1h.json
//
// Scaled-down smoke (what the CI [Fact] runs):
//   ... -- --sites 2 --instances-per-site 10 --tags-per-instance 5 \
//          --settle-minutes 0.1 --sustain-minutes 0.2 --sample-seconds 2 \
//          --sf-drain-messages 200 --slow-subscriber-events 2000

var config = HarnessConfig.Parse(args);

Console.WriteLine("ScadaBridge target-scale load harness");
Console.WriteLine($"  sites                {config.Sites}");
Console.WriteLine($"  instances/site       {config.InstancesPerSite}");
Console.WriteLine($"  tags/instance        {config.TagsPerInstance}");
Console.WriteLine($"  total subscriptions  {config.TotalSubscriptions:N0}");
Console.WriteLine($"  nominal update rate  {config.NominalUpdatesPerSecond:N0}/s");
Console.WriteLine($"  settle / sustain     {config.SettleDuration.TotalMinutes:F1} / {config.SustainDuration.TotalMinutes:F1} min");
Console.WriteLine();

using var cancellation = new CancellationTokenSource();
Console.CancelKeyPress += (_, e) =>
{
    e.Cancel = true;
    cancellation.Cancel();
};

try
{
    var result = await HarnessRun.ExecuteAsync(config, Console.WriteLine, cancellation.Token);

    var json = JsonSerializer.Serialize(result, new JsonSerializerOptions { WriteIndented = true });
    await File.WriteAllTextAsync(config.ResultsPath, json, cancellation.Token);

    Console.WriteLine();
    Console.WriteLine(ResultsFormatter.Format(result));
    Console.WriteLine();
    Console.WriteLine($"JSON metrics written to {Path.GetFullPath(config.ResultsPath)}");
    return 0;
}
catch (OperationCanceledException)
{
    Console.Error.WriteLine("Run cancelled.");
    return 130;
}
