using Inspectron.Settings;
using Lindt.Colorballs.Duo.Utils;
using MudBlazor.Services;
using Ninject;
using Ninject.Extensions.ChildKernel;
using VisionBuilder.UI.Blazor;
using VisionBuilder.UI.Camera;
using VisionBuilder.UI.Common;
using VisionBuilder.UI.Common.Plugins;
using VisionBuilder.UI.Common.Processing;
using VisionBuilder.UI.Common.ViewModel;
using VisionBuilder.UI.Console;
using VisionBuilder.UI.IOCommander;
using VisionBuilder.UI.Recipes.HawkeyeRecipe;
using VisionBuilder.UI.Ringbuffer;
using VisionBuilder.UI.Statistics;

const string CAMERA1 = "Camera 1";

var builder = WebApplication.CreateBuilder(args);

builder.Services.AddRazorComponents()
    .AddInteractiveServerComponents();
builder.Services.AddMudServices();

// Parse command line args
CommandLineParser commandLineParser = new CommandLineParser(args);

// Setup settings
InspectronSettings settings = new InspectronSettings(Path.Combine("..", "Data", "Config"));

var mainKernel = VisionBuilder.UI.Common.VisionBuilder.CreateMainKernel(settings);

var profile = commandLineParser.GetStringArgument("profile", 'p');
mainKernel.UsePlugins(profile);

mainKernel
    .UseConsole()
    .UseIOCommander([CAMERA1])
    .UseBlazorServices()
    .RegisterGlobalPlugins();

mainKernel.Get<ILoadingService>().StartLoading("Camera initialization");

// CAMERA 1 //
ChildKernel kernelCamera1 = new ChildKernel(mainKernel);

kernelCamera1
    .RegisterCamera(CAMERA1)
    .UseStatistics(CAMERA1)
    .UseRingbuffer(CAMERA1)
    .UseHawkeyeRecipes(CAMERA1)
    .UseCameraIOCommander(CAMERA1)
    .RegisterCameraPlugins(CAMERA1);

// LOAD SETTINGS //
mainKernel.RegisterSettings();
kernelCamera1.RegisterSettings();
settings.LoadSettings();

// Create camera and bind it (must be after settings are loaded)
kernelCamera1.UseCamera();

// Initialize modules
mainKernel.InitializeModules();
kernelCamera1.InitializeModules();

mainKernel.Get<ILoadingService>().StopLoading("Camera initialization");

var mainWindowVm = mainKernel.Get<MainWindowVM>();
mainWindowVm.SingleCameraVms =
[
    kernelCamera1.Get<SingleCameraVM>()
];

settings.LoadSettings();

// Bridge Ninject → ASP.NET Core DI
builder.Services.AddSingleton(mainKernel);
builder.Services.AddSingleton(mainWindowVm);
builder.Services.AddSingleton(kernelCamera1.Get<SingleCameraVM>());
builder.Services.AddSingleton(mainKernel.Get<VisionBuilder.UI.Common.Services.IPasswordInputService>());

var app = builder.Build();

if (!app.Environment.IsDevelopment())
{
    app.UseExceptionHandler("/Error");
}

app.UseStaticFiles();
app.UseAntiforgery();

app.MapRazorComponents<VisionBuilder.UI.Blazor.Uno.Components.App>()
    .AddInteractiveServerRenderMode()
    .AddAdditionalAssemblies(typeof(VisionBuilder.UI.Blazor.Components.SingleCameraControl).Assembly);

mainWindowVm.OnProgramStarted();

app.Lifetime.ApplicationStopping.Register(() =>
{
    mainWindowVm.OnProgramClosed();
});

app.Run();
