using System.Reflection;
using FrymasterBadgeApp.Services;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging;

namespace FrymasterBadgeApp;

public static class MauiProgram
{
    public static MauiApp CreateMauiApp()
    {
        var builder = MauiApp.CreateBuilder();
        builder
            .UseMauiApp<App>()
            .ConfigureFonts(fonts =>
            {
                fonts.AddFont("OpenSans-Regular.ttf", "OpenSansRegular");
                fonts.AddFont("OpenSans-Semibold.ttf", "OpenSansSemibold");
                fonts.AddFont("LibreBarcode128-Regular.ttf", "BarcodeFont");
            });

        // --- Simplified Configuration Loading ---
        // Instead of GetManifestResourceStream, we use the simpler FileSystem approach
        // if the file is marked as a MauiAsset.
        try
        {
            var configPath = "appsettings.json";
            // Note: MauiAssets in Resources/Raw are accessed at the root of the app package
            using var stream = FileSystem.OpenAppPackageFileAsync(configPath).Result;
            if (stream != null)
            {
                var config = new ConfigurationBuilder().AddJsonStream(stream).Build();
                builder.Configuration.AddConfiguration(config);
            }
        }
        catch (Exception ex)
        {
            System.Diagnostics.Debug.WriteLine($"CONFIG WARNING: {ex.Message}");
            // Don't 'throw' here unless it's truly fatal,
            // otherwise the app won't even start.
        }

        // 1. Register Services
        builder.Services.AddSingleton<SqlService>();
        builder.Services.AddSingleton<PrinterService>();

        // 2. Register Pages (Crucial for constructor injection)
        builder.Services.AddTransient<MainPage>();
        builder.Services.AddTransient<CompanyPage>();
        builder.Services.AddTransient<EmployeePage>();

#if DEBUG
        builder.Logging.AddDebug();
#endif

        return builder.Build();
    }
}
