using EpsonPrintService;
using Inspectron.Epson.PrintServer.ConfigurationSources;

// Load configuration (may be absent on first boot)
var configResult = ConfigurationLoader.TryLoadFromFile();
EpsonPrintServiceConfiguration? activeConfig = null;

if (configResult.Success)
{
    activeConfig = configResult.Config;
    Console.WriteLine($"Configuration loaded.");
    Console.WriteLine($"Restaurant: {activeConfig!.RestaurantId}");
    Console.WriteLine($"API URL: {activeConfig.ApiUrl}");
}
else
{
    Console.WriteLine($"No valid configuration: {configResult.Error}");
    Console.WriteLine("Running in configuration-only mode. Navigate to http://<this-ip> to configure.");
}

var cts = new CancellationTokenSource();
Console.CancelKeyPress += (sender, e) =>
{
    Console.WriteLine("\nShutting down...");
    e.Cancel = true;
    cts.Cancel();
};

// Track print server state for the web UI
PrintServerBootstrapper? bootstrapper = null;

// Start web UI (always runs)
var httpServer = new SimpleHttpServer(
    getConfig: () => activeConfig,
    getIsRunning: () => bootstrapper?.IsRunning ?? false);
_ = Task.Run(() => httpServer.StartAsync(cts.Token));

// Start print server if configured
if (activeConfig != null)
{
    bootstrapper = new PrintServerBootstrapper(activeConfig, cts);
    await bootstrapper.StartAsync();
}

try
{
    await Task.Delay(Timeout.Infinite, cts.Token);
}
catch (TaskCanceledException)
{
    // Expected when Ctrl+C is pressed
}
