using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using MongoDB.Driver;
using Nalu.Jobs;

// ── Graceful shutdown ──────────────────────────────────────────────────────────
using var cts = new CancellationTokenSource();
Console.CancelKeyPress += (_, e) =>
{
    e.Cancel = true;
    Console.WriteLine("Shutdown requested — finishing gracefully...");
    cts.Cancel();
};

// ── Configuration ──────────────────────────────────────────────────────────────
var config = new ConfigurationBuilder()
    .SetBasePath(AppContext.BaseDirectory)
    .AddJsonFile("appsettings.json", optional: true)
    .AddEnvironmentVariables()
    .Build();

bool forceFull = args.Contains("--force-full");

// ── DI ──────────────────────────────────────────────────────────────────────────
var connStr = config["MONGO_CONNECTION_STRING"] ?? "mongodb://localhost:27017";

var services = new ServiceCollection();
services.AddSingleton<IConfiguration>(config);
services.AddSingleton<IMongoClient>(_ => new MongoClient(connStr));
services.AddSingleton<INameImporterJob, NaluNameImporterJob>();
services.AddLogging(b => b.AddConsole().SetMinimumLevel(LogLevel.Information));

await using var provider = services.BuildServiceProvider();

// ── Run ────────────────────────────────────────────────────────────────────────
Console.WriteLine("═══════════════════════════════════════════");
Console.WriteLine("  NALU Name Importer — IBGE Census Names");
Console.WriteLine("═══════════════════════════════════════════");
Console.WriteLine($"  Force : {forceFull}");
Console.WriteLine();

try
{
    var job = provider.GetRequiredService<INameImporterJob>();
    await job.ExecuteAsync(forceFull);
    return 0;
}
catch (OperationCanceledException)
{
    Console.Error.WriteLine("Cancelled.");
    return 1;
}
catch (Exception ex)
{
    Console.Error.WriteLine($"ERROR: {ex.Message}");
    return 1;
}
