using CommunityToolkit.Maui;
using Microsoft.Extensions.Logging;
using Scry.Core.Data;
using Scry.Core.Recognition;
using Scry.Services;
using Scry.ViewModels;
using Scry.Views;

namespace Scry;

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

        // Core Services (from Scry.Core)
        builder.Services.AddSingleton<CardDatabase>(sp =>
        {
            var dbPath = Path.Combine(FileSystem.AppDataDirectory, "card_hashes.db");
            EnsureDatabaseCopied(dbPath);
            return new CardDatabase(dbPath);
        });
        builder.Services.AddSingleton<CardRecognitionService>();

        // App Services
        builder.Services.AddSingleton<ICardRepository, InMemoryCardRepository>();
        builder.Services.AddSingleton<ICardRecognitionService, RealCardRecognitionService>();

        // ViewModels
        builder.Services.AddTransient<ScanViewModel>();
        builder.Services.AddTransient<CollectionViewModel>();
        builder.Services.AddTransient<CardDetailViewModel>();
        builder.Services.AddTransient<SettingsViewModel>();

        // Views
        builder.Services.AddTransient<ScanPage>();
        builder.Services.AddTransient<CollectionPage>();
        builder.Services.AddTransient<CardDetailPage>();
        builder.Services.AddTransient<SettingsPage>();

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

        return builder.Build();
    }

    private static void EnsureDatabaseCopied(string targetPath)
    {
        if (File.Exists(targetPath))
            return;

        try
        {
            using var stream = FileSystem.OpenAppPackageFileAsync("card_hashes.db").GetAwaiter().GetResult();
            using var fileStream = File.Create(targetPath);
            stream.CopyTo(fileStream);
        }
        catch
        {
            // Database not bundled, will be empty
        }
    }
}
