using System.Reflection;
using System.Text;
using CommunityToolkit.Maui;
using FrymasterBadgeApp.Services;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging;

namespace FrymasterBadgeApp;

public static class MauiProgram
{
    public static MauiApp CreateMauiApp()
    {
        AppLogger.Info("MauiProgram: Starting CreateMauiApp");
        var builder = MauiApp.CreateBuilder();

#pragma warning disable CA1416 // Validate platform compatibility
        builder
            .UseMauiCommunityToolkit()
            .UseMauiApp<App>()
            .ConfigureFonts(fonts =>
            {
                fonts.AddFont("OpenSans-Regular.ttf", "OpenSansRegular");
                fonts.AddFont("OpenSans-Semibold.ttf", "OpenSansSemibold");
                fonts.AddFont("LibreBarcode39-Regular.ttf", "BarcodeFont");
            });
#pragma warning restore CA1416 // Validate platform compatibility

        // 1. Load Configuration
        LoadConfiguration(builder);

        // 2. Register Services with Factory
        builder.Services.AddSingleton<SqlService>(sp =>
        {
            var config = sp.GetRequiredService<IConfiguration>();
            var connectionString = config.GetConnectionString("DefaultConnection");

            if (string.IsNullOrEmpty(connectionString))
            {
                AppLogger.Warn(
                    "SqlService: Connection string missing from config. Using HARDCODED FALLBACK."
                );
                // TODO: Replace with your actual SQL Server details
                connectionString =
                    "Server=127.0.0.1;Database=Frymaster;User Id=sa;Password=YourPassword123;TrustServerCertificate=True;";
            }

            return new SqlService(connectionString);
        });

        builder.Services.AddSingleton<PrinterService>();

        // 3. Register Shell and Pages
        builder.Services.AddSingleton<AppShell>();
        builder.Services.AddTransient<EmployeePage>();
        builder.Services.AddTransient<CompanyPage>();
        builder.Services.AddTransient<SettingsPage>();

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

        return builder.Build();
    }

    private static void LoadConfiguration(MauiAppBuilder builder)
    {
        try
        {
            // Standard MAUI way to read Resources\Raw files
            using var stream = FileSystem.OpenAppPackageFileAsync("appsettings.json").Result;
            using var reader = new StreamReader(stream);
            var json = reader.ReadToEnd();

            var config = new ConfigurationBuilder()
                .AddJsonStream(new MemoryStream(Encoding.UTF8.GetBytes(json)))
                .Build();

            builder.Configuration.AddConfiguration(config);
            AppLogger.Info("Config: appsettings.json loaded via FileSystem.");
        }
        catch (Exception ex)
        {
            AppLogger.Warn(
                $"Config: FileSystem load failed ({ex.Message}). Trying Manifest fallback..."
            );
            try
            {
                var assembly = Assembly.GetExecutingAssembly();
                string resourcePath = "FrymasterBadgeApp.Resources.Raw.appsettings.json";
                using var stream = assembly.GetManifestResourceStream(resourcePath);

                if (stream != null)
                {
                    var config = new ConfigurationBuilder().AddJsonStream(stream).Build();
                    builder.Configuration.AddConfiguration(config);
                    AppLogger.Info("Config: Loaded via Manifest fallback.");
                }
            }
            catch
            { /* Final fallback to hardcoded string in SqlService factory */
            }
        }
    }
}
