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", RawTags = ModbusRawTags.Entries(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();
    }

    // ---- Gap: String array + BitInRegister array decode ----

    /// <summary>
    ///     Verifies that a String array (N string elements backed by contiguous register blocks)
    ///     decodes to a <c>string[]</c>. Each element occupies <c>(StringLength+1)/2</c>
    ///     registers packed high-byte-first (standard HighByteFirst order).
    /// </summary>
    [Fact]
    public async Task Read_String_Array_Returns_String_Array()
    {
        // 3-element array of 4-char strings → each element = 2 registers = 4 bytes.
        // "AB" → reg0_hi='A'(0x41), reg0_lo='B'(0x42), reg1_hi=0x00, reg1_lo=0x00
        // "CD" → reg2_hi='C'(0x43), reg2_lo='D'(0x44), reg3_hi=0x00, reg3_lo=0x00
        // "EF" → reg4_hi='E'(0x45), reg4_lo='F'(0x46), reg5_hi=0x00, reg5_lo=0x00
        // StringLength=4 means 4 chars max; "AB" uses 2 then nul-terminates at index 2.
        var tag = new ModbusTagDefinition("Names", ModbusRegion.HoldingRegisters, 0,
            ModbusDataType.String, StringLength: 4, ArrayCount: 3);
        var (drv, fake) = NewDriver(tag);
        // Element 0: "AB\0\0" → reg0=(0x41<<8|0x42)=0x4142, reg1=0x0000
        fake.HoldingRegisters[0] = 0x4142; // 'A','B'
        fake.HoldingRegisters[1] = 0x0000; // nul nul
        // Element 1: "CD\0\0" → reg2=0x4344, reg3=0x0000
        fake.HoldingRegisters[2] = 0x4344; // 'C','D'
        fake.HoldingRegisters[3] = 0x0000;
        // Element 2: "EF\0\0" → reg4=0x4546, reg5=0x0000
        fake.HoldingRegisters[4] = 0x4546; // 'E','F'
        fake.HoldingRegisters[5] = 0x0000;
        await drv.InitializeAsync("{}", CancellationToken.None);

        var values = await drv.ReadAsync(["Names"], CancellationToken.None);
        var arr = values[0].Value.ShouldBeOfType<string[]>();
        arr.Length.ShouldBe(3);
        arr[0].ShouldBe("AB");
        arr[1].ShouldBe("CD");
        arr[2].ShouldBe("EF");
    }

    /// <summary>
    ///     Verifies that a String array with full-length strings (no nul terminator within the
    ///     element block) decodes correctly.
    /// </summary>
    [Fact]
    public async Task Read_String_Array_Full_Length_Elements()
    {
        // 2-element array of 2-char strings → each element = 1 register = 2 bytes.
        // "AB" → reg0=(0x41<<8|0x42), "CD" → reg1=(0x43<<8|0x44)
        var tag = new ModbusTagDefinition("Codes", ModbusRegion.HoldingRegisters, 10,
            ModbusDataType.String, StringLength: 2, ArrayCount: 2);
        var (drv, fake) = NewDriver(tag);
        fake.HoldingRegisters[10] = 0x4142; // "AB"
        fake.HoldingRegisters[11] = 0x4344; // "CD"
        await drv.InitializeAsync("{}", CancellationToken.None);

        var values = await drv.ReadAsync(["Codes"], CancellationToken.None);
        var arr = values[0].Value.ShouldBeOfType<string[]>();
        arr.ShouldBe(new[] { "AB", "CD" });
    }

    /// <summary>
    ///     Verifies that a BitInRegister array (N register-backed bits at the same bit position)
    ///     decodes to a <c>bool[]</c>. Each element is 1 register; the same BitIndex is applied
    ///     to each.
    /// </summary>
    [Fact]
    public async Task Read_BitInRegister_Array_Returns_Bool_Array()
    {
        // 4-element BitInRegister array at bit 3 (0-based).
        // reg0 = 0x0008 → bit3=1, reg1 = 0x0000 → bit3=0,
        // reg2 = 0x000F → bit3=1, reg3 = 0x0001 → bit3=0
        var tag = new ModbusTagDefinition("Bits", ModbusRegion.HoldingRegisters, 5,
            ModbusDataType.BitInRegister, BitIndex: 3, ArrayCount: 4);
        var (drv, fake) = NewDriver(tag);
        fake.HoldingRegisters[5] = 0x0008; // bit3 = 1
        fake.HoldingRegisters[6] = 0x0000; // bit3 = 0
        fake.HoldingRegisters[7] = 0x000F; // bit3 = 1
        fake.HoldingRegisters[8] = 0x0001; // bit3 = 0
        await drv.InitializeAsync("{}", CancellationToken.None);

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

    /// <summary>
    ///     Verifies that a BitInRegister array at bit 0 correctly distinguishes set / clear.
    /// </summary>
    [Fact]
    public async Task Read_BitInRegister_Array_Bit0_Returns_Bool_Array()
    {
        var tag = new ModbusTagDefinition("Lsb", ModbusRegion.HoldingRegisters, 0,
            ModbusDataType.BitInRegister, BitIndex: 0, ArrayCount: 3);
        var (drv, fake) = NewDriver(tag);
        fake.HoldingRegisters[0] = 0x0001; // bit0 = 1
        fake.HoldingRegisters[1] = 0x0002; // bit0 = 0
        fake.HoldingRegisters[2] = 0xFFFF; // bit0 = 1
        await drv.InitializeAsync("{}", CancellationToken.None);

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

    // ---- Gap: equipment-tag resolver threads arrayLength → ArrayCount ----

    /// <summary>
    ///     Verifies that the equipment-tag parser threads <c>arrayLength</c> from the TagConfig
    ///     JSON blob into <c>ModbusTagDefinition.ArrayCount</c> so that an <c>isArray</c>
    ///     equipment tag reads the correct number of elements as an array.
    /// </summary>
    [Fact]
    public async Task Equipment_Tag_With_ArrayLength_Reads_As_Array()
    {
        var json = """{"region":"HoldingRegisters","address":20,"dataType":"Int16","byteOrder":"BigEndian","bitIndex":0,"stringLength":0,"isArray":true,"arrayLength":3}""";
        var fake = new ModbusDriverTests.FakeTransport();
        var opts = new ModbusDriverOptions { Host = "fake", RawTags = [new RawTagEntry("cell/modbus/arr20", json, false)] };
        var drv = new ModbusDriver(opts, "modbus-eq-arr", _ => fake);
        await drv.InitializeAsync("{}", CancellationToken.None);
        fake.HoldingRegisters[20] = 100;
        fake.HoldingRegisters[21] = 200;
        fake.HoldingRegisters[22] = 300;

        var r = await drv.ReadAsync(["cell/modbus/arr20"], CancellationToken.None);

        r[0].StatusCode.ShouldBe(0u);
        var arr = r[0].Value.ShouldBeOfType<short[]>();
        arr.ShouldBe(new short[] { 100, 200, 300 });
    }

    /// <summary>
    ///     Verifies that an equipment-tag without <c>arrayLength</c> (or <c>arrayLength=0</c>)
    ///     still reads as a scalar (regression guard).
    /// </summary>
    [Fact]
    public async Task Equipment_Tag_Without_ArrayLength_Reads_As_Scalar()
    {
        var json = """{"region":"HoldingRegisters","address":30,"dataType":"UInt16","byteOrder":"BigEndian","bitIndex":0,"stringLength":0}""";
        var fake = new ModbusDriverTests.FakeTransport();
        var opts = new ModbusDriverOptions { Host = "fake", RawTags = [new RawTagEntry("cell/modbus/scalar30", json, false)] };
        var drv = new ModbusDriver(opts, "modbus-eq-scalar", _ => fake);
        await drv.InitializeAsync("{}", CancellationToken.None);
        fake.HoldingRegisters[30] = 1234;

        var r = await drv.ReadAsync(["cell/modbus/scalar30"], CancellationToken.None);

        r[0].StatusCode.ShouldBe(0u);
        r[0].Value.ShouldBe((ushort)1234);
    }

    /// <summary>
    ///     Verifies that the equipment-tag parser correctly reads the parsed <c>ArrayCount</c>
    ///     value when <c>arrayLength</c> is present in the JSON blob.
    /// </summary>
    [Fact]
    public void Equipment_Tag_Parser_Threads_ArrayLength_Into_ArrayCount()
    {
        var json = """{"region":"HoldingRegisters","address":0,"dataType":"Int16","byteOrder":"BigEndian","bitIndex":0,"stringLength":0,"isArray":true,"arrayLength":5}""";
        ModbusTagDefinitionFactory.FromTagConfig(json, "cell/modbus/arr", out var def).ShouldBeTrue();
        def!.ArrayCount.ShouldBe(5);
    }

    /// <summary>
    ///     Verifies that the equipment-tag parser leaves <c>ArrayCount</c> null when
    ///     <c>arrayLength</c> is absent or zero.
    /// </summary>
    [Fact]
    public void Equipment_Tag_Parser_No_ArrayLength_Leaves_ArrayCount_Null()
    {
        var json = """{"region":"HoldingRegisters","address":0,"dataType":"Int16","byteOrder":"BigEndian","bitIndex":0,"stringLength":0}""";
        ModbusTagDefinitionFactory.FromTagConfig(json, "cell/modbus/arr", out var def).ShouldBeTrue();
        def!.ArrayCount.ShouldBeNull();
    }

    // ---- C-1 regression tests: isArray gate ----

    /// <summary>
    ///     C-1 regression: <c>isArray:false</c> with a non-zero <c>arrayLength</c> must produce
    ///     <c>ArrayCount == null</c> (scalar), NOT an array. The foundation materialises a scalar
    ///     node when <c>isArray</c> is false; if the driver returned an array the value-shape
    ///     would mismatch and the OPC UA write would be rejected.
    /// </summary>
    [Fact]
    public void Parser_IsArrayFalse_With_ArrayLength_Gives_Null_ArrayCount()
    {
        // isArray:false, arrayLength:8 → must be scalar (ArrayCount == null).
        var json = """{"region":"HoldingRegisters","address":0,"dataType":"Int16","byteOrder":"BigEndian","bitIndex":0,"stringLength":0,"isArray":false,"arrayLength":8}""";
        ModbusTagDefinitionFactory.FromTagConfig(json, "cell/modbus/arr", out var def).ShouldBeTrue();
        def!.ArrayCount.ShouldBeNull();
    }

    /// <summary>
    ///     C-1 regression: <c>isArray:false</c> with <c>arrayLength:8</c> must read as a SCALAR,
    ///     not as an 8-element array.
    /// </summary>
    [Fact]
    public async Task Equipment_Tag_IsArrayFalse_With_ArrayLength_Reads_As_Scalar()
    {
        // isArray:false, arrayLength:8 → scalar read; only register[40] is consumed.
        var json = """{"region":"HoldingRegisters","address":40,"dataType":"Int16","byteOrder":"BigEndian","bitIndex":0,"stringLength":0,"isArray":false,"arrayLength":8}""";
        var fake = new ModbusDriverTests.FakeTransport();
        var opts = new ModbusDriverOptions { Host = "fake", RawTags = [new RawTagEntry("cell/modbus/c1scalar40", json, false)] };
        var drv = new ModbusDriver(opts, "modbus-c1-scalar", _ => fake);
        await drv.InitializeAsync("{}", CancellationToken.None);
        fake.HoldingRegisters[40] = 9999;

        var r = await drv.ReadAsync(["cell/modbus/c1scalar40"], CancellationToken.None);

        r[0].StatusCode.ShouldBe(0u);
        // Must be a scalar short, NOT a short[].
        r[0].Value.ShouldBeOfType<short>();
        r[0].Value.ShouldBe((short)9999);
    }

    /// <summary>
    ///     Verifies that <c>isArray:true, arrayLength:1</c> produces <c>ArrayCount == 1</c>
    ///     (a valid 1-element array — the canonical rule says arrayLength &gt;= 1 is valid).
    /// </summary>
    [Fact]
    public void Parser_IsArrayTrue_ArrayLength1_Gives_ArrayCount_1()
    {
        var json = """{"region":"HoldingRegisters","address":0,"dataType":"Int16","byteOrder":"BigEndian","bitIndex":0,"stringLength":0,"isArray":true,"arrayLength":1}""";
        ModbusTagDefinitionFactory.FromTagConfig(json, "cell/modbus/arr", out var def).ShouldBeTrue();
        def!.ArrayCount.ShouldBe(1);
    }

    /// <summary>
    ///     Verifies that <c>isArray:true, arrayLength:1</c> reads as a 1-ELEMENT array (not a
    ///     scalar). The foundation materialises a <c>[1]</c> OPC UA array node for this tag.
    /// </summary>
    [Fact]
    public async Task Equipment_Tag_IsArrayTrue_ArrayLength1_Reads_As_One_Element_Array()
    {
        var json = """{"region":"HoldingRegisters","address":50,"dataType":"Int16","byteOrder":"BigEndian","bitIndex":0,"stringLength":0,"isArray":true,"arrayLength":1}""";
        var fake = new ModbusDriverTests.FakeTransport();
        var opts = new ModbusDriverOptions { Host = "fake", RawTags = [new RawTagEntry("cell/modbus/c1arr50", json, false)] };
        var drv = new ModbusDriver(opts, "modbus-c1-arr1", _ => fake);
        await drv.InitializeAsync("{}", CancellationToken.None);
        fake.HoldingRegisters[50] = 777;

        var r = await drv.ReadAsync(["cell/modbus/c1arr50"], CancellationToken.None);

        r[0].StatusCode.ShouldBe(0u);
        // Must be a short[] of length 1, NOT a scalar short.
        var arr = r[0].Value.ShouldBeOfType<short[]>();
        arr.Length.ShouldBe(1);
        arr[0].ShouldBe((short)777);
    }

    /// <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");
        }
    }
}
