using RioJoy.Core.Overlay;
using RioJoy.Overlay;
using SkiaSharp;
using Xunit;

namespace RioJoy.Core.Tests.Overlay;

/// <summary>
/// Full Phase-7 pipeline on the real cockpit assets: extracted regions.json + the
/// exported riojoy.png + the legacy TEST.data labels → a rendered wallpaper. Proves
/// the extract → import → lay out → rasterize chain end to end (headless).
/// </summary>
public class OverlayRenderIntegrationTests
{
    private static bool RegionDiffers(SKBitmap a, SKBitmap b, OverlayRegion r)
    {
        int x0 = (int)r.X, y0 = (int)r.Y;
        int x1 = Math.Min(a.Width, (int)(r.X + r.Width));
        int y1 = Math.Min(a.Height, (int)(r.Y + r.Height));
        for (int y = y0; y < y1; y++)
        for (int x = x0; x < x1; x++)
            if (a.GetPixel(x, y) != b.GetPixel(x, y))
                return true;
        return false;
    }

    [Fact]
    public void RendersCockpitWallpaper_FromRealAssets()
    {
        OverlayTemplate template = OverlayTemplateStore.Load(TestRepo.CustomBackground("regions.json"));
        Assert.False(string.IsNullOrWhiteSpace(template.BaseImagePath));

        using SKBitmap baseImg = SKBitmap.Decode(TestRepo.CustomBackground(template.BaseImagePath!));
        Assert.NotNull(baseImg);
        Assert.Equal(template.Width, baseImg.Width);
        Assert.Equal(template.Height, baseImg.Height);

        IDictionary<string, string> labels =
            GoobieDataImporter.LabelsForRow(GoobieDataImporter.Load(TestRepo.CustomBackground("TEST.data")));

        using SKBitmap rendered = new SkiaOverlayRenderer().Render(template, labels, baseImg);

        Assert.Equal(2720, rendered.Width);
        Assert.Equal(600, rendered.Height);

        // A labeled cell ("b-00" -> "LSDI") must have changed from the base.
        OverlayRegion b00 = template.FindRegion("b-00")!;
        Assert.True(RegionDiffers(baseImg, rendered, b00), "labelled region b-00 should differ from the base image");
    }
}
