using Mbproxy;
using Mbproxy.Proxy;
using Microsoft.Extensions.Hosting.WindowsServices;

var builder = Host.CreateApplicationBuilder(args);

// Windows Service support; no-op when running under dotnet run / console.
builder.Services.AddWindowsService();

// Wire EventLogBridge only when actually running as a Windows Service.
bool isWindowsService = WindowsServiceHelpers.IsWindowsService();

// Wire up structured config, Serilog, and typed options.
builder.AddMbproxySerilog(addEventLogBridge: isWindowsService);
builder.AddMbproxyOptions();

// PDU pipeline: BcdPduPipeline is stateless (per-call correlation flows through
// PerPlcContext.CurrentRequest set by the multiplexer); registering as singleton is fine
// and avoids repeated construction.
builder.Services.AddSingleton<IPduPipeline, BcdPduPipeline>();

// Proxy worker — owns all PlcListeners, logs mbproxy.startup.ready, and drives the admin
// endpoint's lifecycle. Registered as singleton so StatusSnapshotBuilder can inject
// ProxyWorker directly and access its Supervisors dictionary.
builder.Services.AddSingleton<ProxyWorker>();
builder.Services.AddHostedService(sp => sp.GetRequiredService<ProxyWorker>());

// Admin endpoint (Kestrel read-only status page). Not registered as IHostedService —
// ProxyWorker drives its lifecycle so admin starts after listeners and stops AFTER the
// in-flight drain.
builder.AddMbproxyAdmin();

await builder.Build().RunAsync();
