using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using NexusReader.Application.Abstractions.Services;
using NexusReader.Infrastructure.Mobile.Services;
using NexusReader.UI.Shared.Services;
using NexusReader.Application;
using MediatR;
using NexusReader.Maui.Infrastructure.Logging;
using NexusReader.Maui.Infrastructure.Identity;

namespace NexusReader.Maui;

public static class MauiProgram
{
	public static MauiApp CreateMauiApp()
	{
		try
		{
			var builder = MauiApp.CreateBuilder();

			// Load embedded appsettings.json configuration
			var assembly = typeof(App).Assembly;
			using (var stream = assembly.GetManifestResourceStream("NexusReader.Maui.appsettings.json"))
			{
				if (stream != null)
				{
					((IConfigurationBuilder)builder.Configuration).AddJsonStream(stream);
				}
			}

			builder
				.UseMauiApp<App>()
				.RegisterLogging();

			builder.Services.AddMauiBlazorWebView();

#if DEBUG
			builder.Services.AddBlazorWebViewDeveloperTools();
#endif

			// Interception bridge for JS/Blazor WebView logs
			builder.Services.AddSingleton<BlazorLoggingBridge>();

			// Minimal Infrastructure
			builder.Services.AddSingleton<IPlatformService, MauiPlatformService>();
			builder.Services.AddSingleton<INativeStorageService, MauiStorageService>();
			
			// Minimal Identity (Safe Mode)
			builder.Services.AddScoped<NexusAuthenticationStateProvider>();
			builder.Services.AddScoped<Microsoft.AspNetCore.Components.Authorization.AuthenticationStateProvider>(sp => 
				sp.GetRequiredService<NexusAuthenticationStateProvider>());
			builder.Services.AddAuthorizationCore();

			// Basic Network with Secure Token Handler
			builder.Services.AddTransient<MobileAuthenticationHeaderHandler>();
			builder.Services.AddHttpClient("NexusAPI", client =>
			{
				var apiBaseUrl = builder.Configuration["ApiSettings:BaseUrl"] ?? "http://localhost:5000";
				client.BaseAddress = new Uri(apiBaseUrl);
			}).AddHttpMessageHandler<MobileAuthenticationHeaderHandler>();

			builder.Services.AddScoped(sp => sp.GetRequiredService<IHttpClientFactory>().CreateClient("NexusAPI"));

			// UI State
			builder.Services.AddScoped<IThemeService, ThemeService>();
			builder.Services.AddScoped<IFocusModeService, FocusModeService>();
			builder.Services.AddScoped<IQuizStateService, QuizStateService>();
			builder.Services.AddScoped<IReaderNavigationService, ReaderNavigationService>();
			builder.Services.AddScoped<IKnowledgeGraphService, KnowledgeGraphService>();
			builder.Services.AddScoped<IReaderInteractionService, ReaderInteractionService>();
			builder.Services.AddScoped<KnowledgeCoordinator>();
			builder.Services.AddScoped<ISyncService, SyncService>();
			builder.Services.AddScoped<IIdentityService, IdentityService>();
			
			builder.Services.AddApplication();
			
			builder.Services.AddMediatR(cfg => cfg.RegisterServicesFromAssemblies(
				NexusReader.Application.DependencyInjection.Assembly
			));

			return builder.Build();
		}
		catch (Exception ex)
		{
			// This might help the debugger catch the exception more reliably
			System.Diagnostics.Debug.WriteLine($"MAUI Startup Error: {ex}");
			throw;
		}
	}
}
