using Shouldly;
using Xunit;
using ZB.MOM.WW.OtOpcUa.Core.Abstractions;

namespace ZB.MOM.WW.OtOpcUa.Driver.Modbus.Tests;

/// <summary>
///     Round-trip coverage for #137 array support — read N consecutive registers (or coils)
///     and surface them as a typed OPC UA array. Builds on the FakeTransport in
///     <see cref="ModbusDriverTests"/>; tests are co-located with the rest of the in-memory
///     driver coverage so they all share the same harness.
/// </summary>
[Trait("Category", "Unit")]
public sealed class ModbusArrayTests
{
    private static (ModbusDriver driver, ModbusDriverTests.FakeTransport fake) NewDriver(params ModbusTagDefinition[] tags)
    {
        var fake = new ModbusDriverTests.FakeTransport();
        var opts = new ModbusDriverOptions { Host = "fake", Tags = tags };
        var drv = new ModbusDriver(opts, "modbus-array", _ => fake);
        return (drv, fake);
    }

    /// <summary>Verifies reading an Int16 array returns a typed array.</summary>
    [Fact]
    public async Task Read_Int16_Array_Returns_Typed_Array()
    {
        var tag = new ModbusTagDefinition("Levels", ModbusRegion.HoldingRegisters, 0, ModbusDataType.Int16, ArrayCount: 5);
        var (drv, fake) = NewDriver(tag);
        for (var i = 0; i < 5; i++) fake.HoldingRegisters[i] = (ushort)(100 + i);
        await drv.InitializeAsync("{}", CancellationToken.None);

        var values = await drv.ReadAsync(["Levels"], CancellationToken.None);
        var arr = values[0].Value.ShouldBeOfType<short[]>();
        arr.ShouldBe(new short[] { 100, 101, 102, 103, 104 });
    }

    /// <summary>Verifies reading a Float32 array with word swap returns a typed array.</summary>
    [Fact]
    public async Task Read_Float32_Array_Returns_Typed_Array_With_WordSwap()
    {
        var tag = new ModbusTagDefinition("Temps", ModbusRegion.HoldingRegisters, 10, ModbusDataType.Float32,
            ArrayCount: 3, ByteOrder: ModbusByteOrder.WordSwap);
        var (drv, fake) = NewDriver(tag);

        // Pre-encode 3 floats into the fake bank using the matching CDAB layout.
        // Float 1.5f = 0x3FC00000; word-swap → low word in high reg pair: reg0=0x0000, reg1=0x3FC0.
        // Loop encodes 1.5, 2.5, 3.5.
        var src = new[] { 1.5f, 2.5f, 3.5f };
        for (var i = 0; i < src.Length; i++)
        {
            var bytes = BitConverter.GetBytes(src[i]);
            // BitConverter is little-endian on x86; rearrange to big-endian register pair.
            // CDAB means: reg(addr+0) holds bytes[1..0] (low word), reg(addr+1) holds bytes[3..2] (high word).
            fake.HoldingRegisters[10 + i * 2 + 0] = (ushort)((bytes[1] << 8) | bytes[0]);
            fake.HoldingRegisters[10 + i * 2 + 1] = (ushort)((bytes[3] << 8) | bytes[2]);
        }
        await drv.InitializeAsync("{}", CancellationToken.None);

        var values = await drv.ReadAsync(["Temps"], CancellationToken.None);
        var arr = values[0].Value.ShouldBeOfType<float[]>();
        arr.ShouldBe(src);
    }

    /// <summary>Verifies reading a coil array returns a bool array.</summary>
    [Fact]
    public async Task Read_Coil_Array_Returns_Bool_Array()
    {
        var tag = new ModbusTagDefinition("Flags", ModbusRegion.Coils, 0, ModbusDataType.Bool, ArrayCount: 10);
        var (drv, fake) = NewDriver(tag);
        // alternating pattern: T F T F T F T F T F
        for (var i = 0; i < 10; i++) fake.Coils[i] = i % 2 == 0;
        await drv.InitializeAsync("{}", CancellationToken.None);

        var values = await drv.ReadAsync(["Flags"], CancellationToken.None);
        var arr = values[0].Value.ShouldBeOfType<bool[]>();
        arr.ShouldBe(new[] { true, false, true, false, true, false, true, false, true, false });
    }

    /// <summary>Verifies writing an Int16 array lands contiguously in the register bank.</summary>
    [Fact]
    public async Task Write_Int16_Array_Lands_Contiguous_In_Bank()
    {
        var tag = new ModbusTagDefinition("Setpoints", ModbusRegion.HoldingRegisters, 50, ModbusDataType.Int16, ArrayCount: 4);
        var (drv, fake) = NewDriver(tag);
        await drv.InitializeAsync("{}", CancellationToken.None);

        var write = new[] { (short)10, (short)20, (short)30, (short)40 };
        var results = await drv.WriteAsync(
            new[] { new WriteRequest("Setpoints", write) },
            CancellationToken.None);

        results[0].StatusCode.ShouldBe(0u);
        for (var i = 0; i < 4; i++)
            fake.HoldingRegisters[50 + i].ShouldBe((ushort)write[i]);
    }

    /// <summary>Verifies writing a coil array packs bits in LSB-first order.</summary>
    [Fact]
    public async Task Write_Coil_Array_Packs_LSB_First()
    {
        var tag = new ModbusTagDefinition("Outputs", ModbusRegion.Coils, 0, ModbusDataType.Bool, ArrayCount: 10);
        var (drv, fake) = NewDriver(tag);
        await drv.InitializeAsync("{}", CancellationToken.None);

        var pattern = new[] { true, true, false, true, false, false, true, false, true, true };
        var results = await drv.WriteAsync(
            new[] { new WriteRequest("Outputs", pattern) },
            CancellationToken.None);

        results[0].StatusCode.ShouldBe(0u);
        for (var i = 0; i < pattern.Length; i++)
            fake.Coils[i].ShouldBe(pattern[i]);
    }

    /// <summary>Verifies writing an array with mismatched length surfaces an error.</summary>
    [Fact]
    public async Task Write_Array_Mismatch_Length_Surfaces_Error()
    {
        var tag = new ModbusTagDefinition("Setpoints", ModbusRegion.HoldingRegisters, 0, ModbusDataType.Int16, ArrayCount: 4);
        var (drv, _) = NewDriver(tag);
        await drv.InitializeAsync("{}", CancellationToken.None);

        var results = await drv.WriteAsync(
            new[] { new WriteRequest("Setpoints", new short[] { 1, 2, 3 }) }, // 3 != 4
            CancellationToken.None);

        results[0].StatusCode.ShouldNotBe(0u);
    }

    /// <summary>Verifies discovery surfaces IsArray and ArrayDim correctly.</summary>
    [Fact]
    public async Task Discovery_Surfaces_IsArray_And_ArrayDim()
    {
        var tag = new ModbusTagDefinition("Vector", ModbusRegion.HoldingRegisters, 0, ModbusDataType.Float32, ArrayCount: 8);
        var (drv, _) = NewDriver(tag);
        await drv.InitializeAsync("{}", CancellationToken.None);

        var captured = new List<DriverAttributeInfo>();
        await drv.DiscoverAsync(new RecordingBuilder(captured), CancellationToken.None);

        captured.Count.ShouldBe(1);
        captured[0].IsArray.ShouldBeTrue();
        captured[0].ArrayDim.ShouldBe(8u);
    }

    /// <summary>Verifies scalar tag discovery keeps IsArray false.</summary>
    [Fact]
    public async Task Scalar_Tag_Discovery_Stays_NonArray()
    {
        // Regression guard: scalar tags must keep IsArray=false / ArrayDim=null.
        var tag = new ModbusTagDefinition("Single", ModbusRegion.HoldingRegisters, 0, ModbusDataType.Int16);
        var (drv, _) = NewDriver(tag);
        await drv.InitializeAsync("{}", CancellationToken.None);

        var captured = new List<DriverAttributeInfo>();
        await drv.DiscoverAsync(new RecordingBuilder(captured), CancellationToken.None);

        captured[0].IsArray.ShouldBeFalse();
        captured[0].ArrayDim.ShouldBeNull();
    }

    /// <summary>Recording address space builder for capturing discovered attributes.</summary>
    /// <param name="captured">List to capture discovered attributes into.</param>
    private sealed class RecordingBuilder(List<DriverAttributeInfo> captured) : IAddressSpaceBuilder
    {
        /// <summary>Creates a folder in the address space.</summary>
        /// <param name="browseName">The browse name of the folder.</param>
        /// <param name="displayName">The display name of the folder.</param>
        /// <returns>This builder instance.</returns>
        public IAddressSpaceBuilder Folder(string browseName, string displayName) => this;

        /// <summary>Creates a variable in the address space.</summary>
        /// <param name="browseName">The browse name of the variable.</param>
        /// <param name="displayName">The display name of the variable.</param>
        /// <param name="attributeInfo">The attribute information.</param>
        /// <returns>A variable handle.</returns>
        public IVariableHandle Variable(string browseName, string displayName, DriverAttributeInfo attributeInfo)
        {
            captured.Add(attributeInfo);
            return new StubHandle(browseName);
        }

        /// <summary>Adds a property to the current node.</summary>
        /// <param name="browseName">The browse name of the property.</param>
        /// <param name="dataType">The data type of the property.</param>
        /// <param name="value">The property value.</param>
        public void AddProperty(string browseName, DriverDataType dataType, object? value) { }

        /// <summary>Stub variable handle for testing.</summary>
        /// <param name="fullRef">The full reference of the handle.</param>
        private sealed class StubHandle(string fullRef) : IVariableHandle
        {
            /// <summary>Gets the full reference.</summary>
            public string FullReference => fullRef;

            /// <summary>Marks this variable as an alarm condition.</summary>
            /// <param name="info">The alarm condition information.</param>
            /// <returns>An alarm condition sink.</returns>
            public IAlarmConditionSink MarkAsAlarmCondition(AlarmConditionInfo info)
                => throw new NotSupportedException("RecordingBuilder doesn't model alarms");
        }
    }
}
