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

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

/// <summary>
///     #150 — bisection-style range narrowing for coalescing prohibitions. After a coalesced
///     read fails, the re-probe loop bisects the prohibited range over multiple ticks until
///     it pinpoints the actual protected register(s). Healthy halves get cleared as the
///     bisection narrows.
/// </summary>
[Trait("Category", "Unit")]
public sealed class ModbusCoalescingBisectionTests
{
    /// <summary>
    ///     Programmable transport like the one in ModbusCoalescingAutoRecoveryTests but local
    ///     to keep this test file standalone — having the protection model live next to the
    ///     bisection assertions makes the test intent easier to read.
    /// </summary>
    private sealed class ProtectedHoleTransport : IModbusTransport
    {
        /// <summary>Gets or sets the protected address that will cause read failures.</summary>
        public ushort ProtectedAddress { get; set; } = ushort.MaxValue;
        /// <summary>Simulates connecting to the Modbus device.</summary>
        /// <param name="ct">The cancellation token.</param>
        /// <returns>A completed task.</returns>
        public Task ConnectAsync(CancellationToken ct) => Task.CompletedTask;
        /// <summary>Simulates sending a Modbus PDU and failing if the protected address is accessed.</summary>
        /// <param name="unitId">The Modbus unit ID.</param>
        /// <param name="pdu">The protocol data unit.</param>
        /// <param name="ct">The cancellation token.</param>
        /// <returns>The response PDU or an exception if the protected address is accessed.</returns>
        public Task<byte[]> SendAsync(byte unitId, byte[] pdu, CancellationToken ct)
        {
            var addr = (ushort)((pdu[1] << 8) | pdu[2]);
            var qty = (ushort)((pdu[3] << 8) | pdu[4]);
            if (pdu[0] is 0x03 or 0x04 && ProtectedAddress >= addr && ProtectedAddress < addr + qty)
                return Task.FromException<byte[]>(new ModbusException(pdu[0], 0x02, "IllegalDataAddress"));
            switch (pdu[0])
            {
                case 0x03: case 0x04:
                {
                    var resp = new byte[2 + qty * 2];
                    resp[0] = pdu[0]; resp[1] = (byte)(qty * 2);
                    return Task.FromResult(resp);
                }
                default: return Task.FromResult(new byte[] { pdu[0], 0, 0 });
            }
        }
        /// <summary>Disposes the transport asynchronously.</summary>
        /// <returns>A completed value task.</returns>
        public ValueTask DisposeAsync() => ValueTask.CompletedTask;
    }

    /// <summary>Verifies that bisection narrows a multi-register prohibition on each reprobe cycle.</summary>
    [Fact]
    public async Task Bisection_Narrows_Multi_Register_Prohibition_Per_Reprobe()
    {
        var fake = new ProtectedHoleTransport { ProtectedAddress = 105 };
        // 11 tags 100..110 with MaxReadGap=10 → coalesce into one block 100..110. The protected
        // register is in the middle (105). After the first failure the planner records the
        // full 100..110 range as split-pending. Each subsequent re-probe bisects until the
        // prohibition is pinned at register 105.
        var tags = Enumerable.Range(100, 11)
            .Select(i => new ModbusTagDefinition($"T{i}", ModbusRegion.HoldingRegisters, (ushort)i, ModbusDataType.Int16))
            .ToArray();
        var opts = new ModbusDriverOptions { Host = "f", RawTags = ModbusRawTags.Entries(tags), MaxReadGap = 10,
            AutoProhibitReprobeInterval = TimeSpan.FromMilliseconds(100),
            Probe = new ModbusProbeOptions { Enabled = false } };
        var drv = new ModbusDriver(opts, "m1", _ => fake);
        await drv.InitializeAsync("{}", CancellationToken.None);

        await drv.ReadAsync(tags.Select(t => t.Name).ToArray(), CancellationToken.None);
        // Initial prohibition: full 100..110 range, split-pending.
        drv.AutoProhibitedRangeCount.ShouldBe(1);

        // Re-probe pass 1: bisect 100..110 → mid=105 → left=100..105 (fails because 105 is
        // protected), right=106..110 (succeeds). Result: prohibition collapses to 100..105.
        await drv.RunReprobeOnceForTestAsync(CancellationToken.None);
        drv.AutoProhibitedRangeCount.ShouldBe(1, "after pass 1 the prohibition narrows but doesn't disappear");

        // Re-probe pass 2: bisect 100..105 → mid=102 → left=100..102 (succeeds), right=103..105 (fails).
        // Result: prohibition collapses to 103..105.
        await drv.RunReprobeOnceForTestAsync(CancellationToken.None);

        // Re-probe pass 3: bisect 103..105 → mid=104 → left=103..104 (succeeds), right=105..105 (fails).
        // Result: prohibition collapses to 105..105 (single register, no longer split-pending).
        await drv.RunReprobeOnceForTestAsync(CancellationToken.None);
        drv.AutoProhibitedRangeCount.ShouldBe(1, "single-register prohibition stays after bisection terminates");

        // Re-probe pass 4: 105..105 is single-register; straight-retry path. Still fails;
        // prohibition stays.
        await drv.RunReprobeOnceForTestAsync(CancellationToken.None);
        drv.AutoProhibitedRangeCount.ShouldBe(1);

        await drv.ShutdownAsync(CancellationToken.None);
    }

    /// <summary>Verifies that the prohibition is cleared when both bisected halves succeed in recovery.</summary>
    [Fact]
    public async Task Bisection_Clears_When_Both_Halves_Are_Healthy()
    {
        // Transient failure scenario: range failed once, but by the next re-probe the PLC has
        // unlocked it. Bisection of (100..110) returns success on both halves → entry removed
        // entirely.
        var fake = new ProtectedHoleTransport { ProtectedAddress = 105 };
        var tags = Enumerable.Range(100, 11)
            .Select(i => new ModbusTagDefinition($"T{i}", ModbusRegion.HoldingRegisters, (ushort)i, ModbusDataType.Int16))
            .ToArray();
        var opts = new ModbusDriverOptions { Host = "f", RawTags = ModbusRawTags.Entries(tags), MaxReadGap = 10,
            AutoProhibitReprobeInterval = TimeSpan.FromMilliseconds(100),
            Probe = new ModbusProbeOptions { Enabled = false } };
        var drv = new ModbusDriver(opts, "m1", _ => fake);
        await drv.InitializeAsync("{}", CancellationToken.None);

        await drv.ReadAsync(tags.Select(t => t.Name).ToArray(), CancellationToken.None);
        drv.AutoProhibitedRangeCount.ShouldBe(1);

        // Operator unlocks the protected register before the re-probe runs.
        fake.ProtectedAddress = ushort.MaxValue;

        await drv.RunReprobeOnceForTestAsync(CancellationToken.None);
        drv.AutoProhibitedRangeCount.ShouldBe(0, "both bisected halves succeed → parent prohibition cleared entirely");

        await drv.ShutdownAsync(CancellationToken.None);
    }

    /// <summary>Verifies that the prohibition splits into two entries when both bisected halves still fail.</summary>
    [Fact]
    public async Task Bisection_Splits_Into_Two_When_Both_Halves_Still_Fail()
    {
        // Two protected registers in the same coalesced range: 102 and 108. After bisection,
        // both halves of the original (100..110) range still contain a protected address
        // (left=100..105 contains 102, right=106..110 contains 108). The prohibition replaces
        // the parent with TWO smaller split-pending entries.
        var fake = new ProtectedHoleTransport();
        // Build a more elaborate transport that protects two addresses.
        var twoHole = new TwoHoleTransport { ProtectedAddresses = { 102, 108 } };
        var tags = Enumerable.Range(100, 11)
            .Select(i => new ModbusTagDefinition($"T{i}", ModbusRegion.HoldingRegisters, (ushort)i, ModbusDataType.Int16))
            .ToArray();
        var opts = new ModbusDriverOptions { Host = "f", RawTags = ModbusRawTags.Entries(tags), MaxReadGap = 10,
            AutoProhibitReprobeInterval = TimeSpan.FromMilliseconds(100),
            Probe = new ModbusProbeOptions { Enabled = false } };
        var drv = new ModbusDriver(opts, "m1", _ => twoHole);
        await drv.InitializeAsync("{}", CancellationToken.None);

        await drv.ReadAsync(tags.Select(t => t.Name).ToArray(), CancellationToken.None);
        drv.AutoProhibitedRangeCount.ShouldBe(1);

        // Re-probe: bisect 100..110 at mid=105 → left=100..105 (contains 102, fails),
        // right=106..110 (contains 108, fails). Result: TWO entries in place of the parent.
        await drv.RunReprobeOnceForTestAsync(CancellationToken.None);
        drv.AutoProhibitedRangeCount.ShouldBe(2, "both halves still fail → prohibition splits into two");

        await drv.ShutdownAsync(CancellationToken.None);
    }

    private sealed class TwoHoleTransport : IModbusTransport
    {
        public readonly HashSet<ushort> ProtectedAddresses = new();
        /// <summary>Simulates connecting to the Modbus device.</summary>
        /// <param name="ct">The cancellation token.</param>
        /// <returns>A completed task.</returns>
        public Task ConnectAsync(CancellationToken ct) => Task.CompletedTask;
        /// <summary>Simulates sending a Modbus PDU and failing if any protected address is accessed.</summary>
        /// <param name="unitId">The Modbus unit ID.</param>
        /// <param name="pdu">The protocol data unit.</param>
        /// <param name="ct">The cancellation token.</param>
        /// <returns>The response PDU or an exception if a protected address is accessed.</returns>
        public Task<byte[]> SendAsync(byte unitId, byte[] pdu, CancellationToken ct)
        {
            var addr = (ushort)((pdu[1] << 8) | pdu[2]);
            var qty = (ushort)((pdu[3] << 8) | pdu[4]);
            if (pdu[0] is 0x03 or 0x04)
                for (var i = 0; i < qty; i++)
                    if (ProtectedAddresses.Contains((ushort)(addr + i)))
                        return Task.FromException<byte[]>(new ModbusException(pdu[0], 0x02, "IllegalDataAddress"));
            switch (pdu[0])
            {
                case 0x03: case 0x04:
                {
                    var resp = new byte[2 + qty * 2];
                    resp[0] = pdu[0]; resp[1] = (byte)(qty * 2);
                    return Task.FromResult(resp);
                }
                default: return Task.FromResult(new byte[] { pdu[0], 0, 0 });
            }
        }
        /// <summary>Disposes the transport asynchronously.</summary>
        /// <returns>A completed value task.</returns>
        public ValueTask DisposeAsync() => ValueTask.CompletedTask;
    }
}
