using System;
using System.Buffers.Binary;
using System.IO;

namespace Tornado3_2026Election.Services;

public static class KarismaSceneResolutionReader
{
    private const int HeaderScanLength = 1024;
    private const int Float50Bits = 1112014848;
    private const int Float1000Bits = 1148846080;

    public static bool TryRead(string scenePath, out KarismaSceneResolution resolution)
    {
        resolution = default;

        if (string.IsNullOrWhiteSpace(scenePath) || !File.Exists(scenePath))
        {
            return false;
        }

        try
        {
            using var stream = File.OpenRead(scenePath);
            Span<byte> header = stackalloc byte[HeaderScanLength];
            var bytesRead = stream.Read(header);
            if (bytesRead < 16)
            {
                return false;
            }

            var headerSlice = header[..bytesRead];
            for (var offset = 0; offset <= headerSlice.Length - 16; offset += 4)
            {
                var width = BinaryPrimitives.ReadInt32LittleEndian(headerSlice.Slice(offset, 4));
                var height = BinaryPrimitives.ReadInt32LittleEndian(headerSlice.Slice(offset + 4, 4));
                var marker50 = BinaryPrimitives.ReadInt32LittleEndian(headerSlice.Slice(offset + 8, 4));
                var marker1000 = BinaryPrimitives.ReadInt32LittleEndian(headerSlice.Slice(offset + 12, 4));

                if (!IsPlausibleDimension(width, height) ||
                    marker50 != Float50Bits ||
                    marker1000 != Float1000Bits)
                {
                    continue;
                }

                resolution = new KarismaSceneResolution(width, height);
                return true;
            }
        }
        catch
        {
        }

        return false;
    }

    private static bool IsPlausibleDimension(int width, int height)
    {
        return width is >= 320 and <= 20000 &&
               height is >= 180 and <= 12000;
    }
}

public readonly record struct KarismaSceneResolution(int Width, int Height);
