using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using OFACScraper;
using OFACScraper.Configuration;
using OFACScraper.Services;
using Serilog;

var command = args.FirstOrDefault() ?? "ofac-daily";

Log.Logger = new LoggerConfiguration()
    .MinimumLevel.Information()
    .WriteTo.Console(outputTemplate: "[{Timestamp:HH:mm:ss} {Level:u3}] {Message:lj}{NewLine}{Exception}")
    .WriteTo.File("logs/ofac-.log", rollingInterval: RollingInterval.Day,
        outputTemplate: "[{Timestamp:yyyy-MM-dd HH:mm:ss} {Level:u3}] {Message:lj}{NewLine}{Exception}")
    .CreateLogger();

try
{
    Log.Information("OFAC Scraper starting. Command: {Command}", command);

    var host = Host.CreateDefaultBuilder(args)
        .UseSerilog()
        .ConfigureServices((ctx, services) =>
        {
            services.Configure<OFACOptions>(ctx.Configuration.GetSection(OFACOptions.SectionName));
            services.Configure<StorageOptions>(ctx.Configuration.GetSection(StorageOptions.SectionName));
            services.Configure<S3Options>(ctx.Configuration.GetSection(S3Options.SectionName));

            const string userAgent = "Mozilla/5.0 (compatible; OFACBot/1.0; +https://ukdataservices.co.uk)";

            services.AddHttpClient<OFACScraper.OFACScraper>(client =>
            {
                client.DefaultRequestHeaders.Add("User-Agent", userAgent);
                client.Timeout = TimeSpan.FromSeconds(60);
            });

            services.AddHttpClient<Exporter>(client =>
            {
                client.DefaultRequestHeaders.Add("User-Agent", userAgent);
                client.Timeout = TimeSpan.FromSeconds(120);
            });

            services.AddSingleton<S3UploadService>();
            services.AddSingleton<CheckpointStore>();
            services.AddTransient<Application>();
        })
        .Build();

    var app = host.Services.GetRequiredService<Application>();
    var exitCode = command switch
    {
        "ofac-full"  => await app.RunFullAsync(),
        "ofac-daily" => await app.RunDailyAsync(),
        _ => throw new ArgumentException($"Unknown command: {command}. Use ofac-full or ofac-daily.")
    };

    return exitCode;
}
catch (Exception ex)
{
    Log.Fatal(ex, "Unhandled exception");
    return 1;
}
finally
{
    Log.CloseAndFlush();
}
