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

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

/// <summary>
///     #140 protocol-behavior knobs: MaxCoilsPerRead, UseFC15ForSingleCoilWrites,
///     UseFC16ForSingleRegisterWrites, DisableFC23. Coverage focuses on default behaviour
///     (no change from pre-#140) and the wire-FC selection when the knobs are flipped.
/// </summary>
[Trait("Category", "Unit")]
public sealed class ModbusProtocolOptionsTests
{
    private sealed class CapturingTransport : IModbusTransport
    {
        public readonly List<byte[]> Sent = new();
        /// <summary>Asynchronously connects the transport.</summary>
        /// <param name="ct">The cancellation token.</param>
        /// <returns>A completed task.</returns>
        public Task ConnectAsync(CancellationToken ct) => Task.CompletedTask;
        /// <summary>Asynchronously sends a Modbus PDU and returns a response.</summary>
        /// <param name="unitId">The Modbus unit ID.</param>
        /// <param name="pdu">The protocol data unit to send.</param>
        /// <param name="ct">The cancellation token.</param>
        /// <returns>A task that returns the response bytes.</returns>
        public Task<byte[]> SendAsync(byte unitId, byte[] pdu, CancellationToken ct)
        {
            Sent.Add(pdu);
            // Return a minimal valid response per FC. We zero-fill the data slot but size it
            // correctly so the driver's bitmap walker doesn't IndexOutOfRange on chunked reads.
            switch (pdu[0])
            {
                case 0x05: case 0x06: case 0x0F: case 0x10:
                    return Task.FromResult(pdu);                                 // echo
                case 0x01: case 0x02:
                {
                    var qty = (ushort)((pdu[3] << 8) | pdu[4]);
                    var byteCount = (byte)((qty + 7) / 8);
                    var resp = new byte[2 + byteCount];
                    resp[0] = pdu[0]; resp[1] = byteCount;
                    return Task.FromResult(resp);
                }
                case 0x03: case 0x04:
                {
                    var qty = (ushort)((pdu[3] << 8) | pdu[4]);
                    var byteCount = (byte)(qty * 2);
                    var resp = new byte[2 + byteCount];
                    resp[0] = pdu[0]; resp[1] = byteCount;
                    return Task.FromResult(resp);
                }
                default:
                    return Task.FromResult(new byte[] { pdu[0], 0, 0 });
            }
        }
        /// <summary>Asynchronously disposes the transport.</summary>
        /// <returns>A completed task.</returns>
        public ValueTask DisposeAsync() => ValueTask.CompletedTask;
    }

    /// <summary>Verifies that defaults match historical behavior.</summary>
    [Fact]
    public void Defaults_Match_Historical_Behaviour()
    {
        var opts = new ModbusDriverOptions();
        opts.MaxCoilsPerRead.ShouldBe((ushort)2000);
        opts.UseFC15ForSingleCoilWrites.ShouldBeFalse();
        opts.UseFC16ForSingleRegisterWrites.ShouldBeFalse();
        opts.DisableFC23.ShouldBeFalse();
    }

    /// <summary>Verifies that single coil write uses FC05 by default.</summary>
    [Fact]
    public async Task Single_Coil_Write_Uses_FC05_By_Default()
    {
        var fake = new CapturingTransport();
        var tag = new ModbusTagDefinition("Run", ModbusRegion.Coils, 0, ModbusDataType.Bool);
        var drv = new ModbusDriver(new ModbusDriverOptions { Host = "f", RawTags = ModbusRawTags.Entries([tag]), Probe = new ModbusProbeOptions { Enabled = false } }, "m1", _ => fake);
        await drv.InitializeAsync("{}", CancellationToken.None);

        await drv.WriteAsync([new WriteRequest("Run", true)], CancellationToken.None);

        fake.Sent.Last()[0].ShouldBe((byte)0x05); // FC05 Write Single Coil
    }

    /// <summary>Verifies that single coil write uses FC15 when forced.</summary>
    [Fact]
    public async Task Single_Coil_Write_Uses_FC15_When_Forced()
    {
        var fake = new CapturingTransport();
        var tag = new ModbusTagDefinition("Run", ModbusRegion.Coils, 0, ModbusDataType.Bool);
        var opts = new ModbusDriverOptions { Host = "f", RawTags = ModbusRawTags.Entries([tag]), UseFC15ForSingleCoilWrites = true, Probe = new ModbusProbeOptions { Enabled = false } };
        var drv = new ModbusDriver(opts, "m1", _ => fake);
        await drv.InitializeAsync("{}", CancellationToken.None);

        await drv.WriteAsync([new WriteRequest("Run", true)], CancellationToken.None);

        fake.Sent.Last()[0].ShouldBe((byte)0x0F); // FC15 Write Multiple Coils
    }

    /// <summary>Verifies that single register write uses FC06 by default.</summary>
    [Fact]
    public async Task Single_Register_Write_Uses_FC06_By_Default()
    {
        var fake = new CapturingTransport();
        var tag = new ModbusTagDefinition("Sp", ModbusRegion.HoldingRegisters, 0, ModbusDataType.Int16);
        var drv = new ModbusDriver(new ModbusDriverOptions { Host = "f", RawTags = ModbusRawTags.Entries([tag]), Probe = new ModbusProbeOptions { Enabled = false } }, "m1", _ => fake);
        await drv.InitializeAsync("{}", CancellationToken.None);

        await drv.WriteAsync([new WriteRequest("Sp", (short)42)], CancellationToken.None);

        fake.Sent.Last()[0].ShouldBe((byte)0x06); // FC06 Write Single Register
    }

    /// <summary>Verifies that single register write uses FC16 when forced.</summary>
    [Fact]
    public async Task Single_Register_Write_Uses_FC16_When_Forced()
    {
        var fake = new CapturingTransport();
        var tag = new ModbusTagDefinition("Sp", ModbusRegion.HoldingRegisters, 0, ModbusDataType.Int16);
        var opts = new ModbusDriverOptions { Host = "f", RawTags = ModbusRawTags.Entries([tag]), UseFC16ForSingleRegisterWrites = true, Probe = new ModbusProbeOptions { Enabled = false } };
        var drv = new ModbusDriver(opts, "m1", _ => fake);
        await drv.InitializeAsync("{}", CancellationToken.None);

        await drv.WriteAsync([new WriteRequest("Sp", (short)42)], CancellationToken.None);

        fake.Sent.Last()[0].ShouldBe((byte)0x10); // FC16 Write Multiple Registers
    }

    /// <summary>Verifies that coil array read automatically chunks at MaxCoilsPerRead.</summary>
    [Fact]
    public async Task Coil_Array_Read_Auto_Chunks_At_MaxCoilsPerRead()
    {
        var fake = new CapturingTransport();
        // 2500 coils with cap 2000 → 2 reads (2000 + 500).
        var tag = new ModbusTagDefinition("Big", ModbusRegion.Coils, 0, ModbusDataType.Bool, ArrayCount: 2500);
        var opts = new ModbusDriverOptions { Host = "f", RawTags = ModbusRawTags.Entries([tag]), MaxCoilsPerRead = 2000, Probe = new ModbusProbeOptions { Enabled = false } };
        var drv = new ModbusDriver(opts, "m1", _ => fake);
        await drv.InitializeAsync("{}", CancellationToken.None);

        await drv.ReadAsync(["Big"], CancellationToken.None);

        // Ignore the probe FC03 from InitializeAsync; count only FC01 reads.
        var fc01s = fake.Sent.Where(p => p[0] == 0x01).ToList();
        fc01s.Count.ShouldBe(2);
        // First chunk asks for 2000.
        ((ushort)((fc01s[0][3] << 8) | fc01s[0][4])).ShouldBe((ushort)2000);
        // Second chunk asks for 500.
        ((ushort)((fc01s[1][3] << 8) | fc01s[1][4])).ShouldBe((ushort)500);
    }
}
