using System.Globalization;
using Khaemhat.Application.Instance;
using Khaemhat.Application.Seeding;
using Khaemhat.Core.Instance;
using Khaemhat.Data;
using Khaemhat.Data.Companies;
using Khaemhat.Infrastructure.Logging;
namespace Khaemhat.Web.Hosting;
/// What seed was asked to do.
/// Add the demo data too, after the base data, to the tables still empty.
/// How many times the demo catalogues are repeated.
/// The company, or for every active one.
public sealed record SeedOptions(bool Demo, int Scale, string? Company);
///
/// The command line of scripts/seed.sh (SPEC §4, §14): seed --base|--demo [--scale N] [--company CODE]
/// runs the start sequence without serving anything (migrations, first company), then adds the missing base data, and
/// with --demo the demo data, to one company or to every active one, and prints what it added. Rows already there
/// are never changed (ADR 0026); each demo seeder fills only its tables still empty.
///
public static class SeedCommand
{
/// The first argument that selects the command.
public const string Verb = "seed";
/// Exit code of a wrong command line.
public const int UsageError = 64;
/// The largest --scale.
public const int MaxScale = 100;
/// Whether the arguments ask for this command.
/// The arguments.
/// for seed ....
public static bool Matches(string[] args) => args is [Verb, ..];
/// Reads the options after the verb.
/// The arguments, verb included.
/// What to do, when the line is valid.
/// The problem, or .
/// when the line is valid.
public static bool TryParse(string[] args, out SeedOptions? options, out string? error)
{
ArgumentNullException.ThrowIfNull(args);
options = null;
error = null;
var wantsBase = false;
var wantsDemo = false;
int? scale = null;
string? company = null;
for (var i = 1; i < args.Length; i++)
{
switch (args[i])
{
case "--base":
wantsBase = true;
break;
case "--demo":
wantsDemo = true;
break;
case "--scale" when i + 1 < args.Length && int.TryParse(args[i + 1], NumberStyles.None, CultureInfo.InvariantCulture, out var n) && n is >= 1 and <= MaxScale:
scale = n;
i++;
break;
case "--company" when i + 1 < args.Length && CompanyCodes.IsValid(CompanyCodes.Normalize(args[i + 1])):
company = CompanyCodes.Normalize(args[++i]);
break;
default:
error = "Argomento non valido: " + args[i];
return false;
}
}
if (!wantsBase && !wantsDemo)
{
error = "Uso: seed --base | --demo [--scale N] [--company CODICE]";
return false;
}
if (scale is not null && !wantsDemo)
{
error = "--scale vale solo con --demo.";
return false;
}
options = new SeedOptions(wantsDemo, scale ?? 1, company);
return true;
}
/// Runs the command.
/// The arguments, verb included.
/// The exit code: 0 done, 1 failed, 64 wrong command line.
public static async Task RunAsync(string[] args)
{
if (!TryParse(args, out var options, out var error) || options is null)
{
await Console.Error.WriteLineAsync(error).ConfigureAwait(false);
return UsageError;
}
// The configuration comes from the KHAEMHAT_* variables, as for the service; no web server is started.
var app = KhaemhatApp.Build([]);
await using (app.ConfigureAwait(false))
{
var services = app.Services;
try
{
await services.GetRequiredService().RunAsync().ConfigureAwait(false);
var registry = services.GetRequiredService();
var company = options.Company;
IReadOnlyList codes = company is null
? [.. (await registry.ListAsync().ConfigureAwait(false)).Where(c => c.Status == CompanyStatus.Active).Select(c => c.Code)]
: await registry.FindAsync(company).ConfigureAwait(false) is { } found ? [found.Code] : [];
if (codes.Count == 0)
{
await Console.Error.WriteLineAsync(company is null ? "Nessuna azienda attiva." : "Azienda sconosciuta: " + company).ConfigureAwait(false);
return 1;
}
var runner = services.GetRequiredService();
foreach (var code in codes)
{
// The demo data need the base tables: --demo runs the base seeders first.
var report = await runner.RunAsync(code, SeedKind.Base).ConfigureAwait(false);
Print(code, "dati di base " + report.DataVersion, report);
if (options.Demo)
{
Print(code, "dati dimostrativi, scala " + options.Scale.ToString(CultureInfo.InvariantCulture),
await runner.RunAsync(code, SeedKind.Demo, options.Scale).ConfigureAwait(false));
// The demo documents go through the document engine, after the masters they use.
await services.GetRequiredService().SeedAsync(code, new CompanySeedContext(IsNew: false, Base: false, Demo: true)).ConfigureAwait(false);
await services.GetRequiredService().SeedAsync(code, new CompanySeedContext(IsNew: false, Base: false, Demo: true)).ConfigureAwait(false);
}
}
return 0;
}
finally
{
await services.GetRequiredService().DisposeAsync().ConfigureAwait(false);
}
}
}
private static void Print(string company, string what, SeedReport report)
{
Console.WriteLine(string.Create(CultureInfo.InvariantCulture, $"{company}: {what}, {report.Total} righe aggiunte."));
foreach (var (table, count) in report.Added.Where(a => a.Value > 0).OrderBy(a => a.Key, StringComparer.Ordinal))
{
Console.WriteLine(string.Create(CultureInfo.InvariantCulture, $" {table}: {count}"));
}
}
}