using System.CommandLine; using HaDbMigration.Configuration; using HaDbMigration.Services; using HaDbMigration.Services.Interfaces; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Logging; using Serilog; var sqliteOption = new Option("--sqlite") { Description = "Path to the Home Assistant SQLite database file (home-assistant_v2.db)", Required = true, }; var pgConnectionOption = new Option("--pg-connection") { Description = "PostgreSQL connection string", Required = true, }; var batchSizeOption = new Option("--batch-size") { Description = "Number of rows per batch (minimum 100)", DefaultValueFactory = _ => 10_000, }; var truncateOption = new Option("--truncate") { Description = "Truncate PostgreSQL tables before migration", DefaultValueFactory = _ => false, }; var dryRunOption = new Option("--dry-run") { Description = "Validate only, do not write data", DefaultValueFactory = _ => false, }; var rootCommand = new RootCommand("Home Assistant SQLite to PostgreSQL migration tool"); rootCommand.Options.Add(sqliteOption); rootCommand.Options.Add(pgConnectionOption); rootCommand.Options.Add(batchSizeOption); rootCommand.Options.Add(truncateOption); rootCommand.Options.Add(dryRunOption); rootCommand.SetAction(async (parseResult, cancellationToken) => { var sqlite = parseResult.GetValue(sqliteOption)!; var pgConnection = parseResult.GetValue(pgConnectionOption)!; var batchSize = parseResult.GetValue(batchSizeOption); var truncate = parseResult.GetValue(truncateOption); var dryRun = parseResult.GetValue(dryRunOption); var options = new MigrationOptions { SqlitePath = sqlite, PostgresConnectionString = pgConnection, BatchSize = batchSize, Truncate = truncate, DryRun = dryRun, }; options.Validate(); Log.Logger = new LoggerConfiguration() .MinimumLevel.Information() .WriteTo.Console( outputTemplate: "[{Timestamp:HH:mm:ss} {Level:u3}] {Message:lj}{NewLine}{Exception}") .CreateLogger(); try { var host = Host.CreateDefaultBuilder() .UseSerilog() .ConfigureServices(services => { services.AddSingleton(options); services.AddSingleton(); services.AddSingleton(); services.AddSingleton(); services.AddSingleton(); services.AddSingleton(); }) .Build(); var orchestrator = host.Services.GetRequiredService(); await orchestrator.RunAsync(cancellationToken); } catch (Exception ex) { Log.Fatal(ex, "Migration failed with an unhandled exception"); Environment.ExitCode = 1; } finally { await Log.CloseAndFlushAsync(); } }); var result = rootCommand.Parse(args); return await result.InvokeAsync();