using CliFx.Attributes;
using CliFx.Infrastructure;
using ZB.MOM.WW.OtOpcUa.Core.Abstractions;
using ZB.MOM.WW.OtOpcUa.Driver.Cli.Common;

namespace ZB.MOM.WW.OtOpcUa.Driver.Modbus.Cli.Commands;

/// <summary>
///     Long-running poll of one Modbus register via the driver's <c>ISubscribable</c> surface
///     (under the hood: <c>PollGroupEngine</c>). Prints each data-change event until the
///     operator Ctrl+C's the CLI. Useful for watching a changing PLC signal during
///     commissioning or while reproducing a customer bug.
/// </summary>
[Command("subscribe", Description = "Watch a Modbus register via polled subscription until Ctrl+C.")]
public sealed class SubscribeCommand : ModbusCommandBase
{
    [CommandOption("region", 'r', Description =
        "Coils / DiscreteInputs / InputRegisters / HoldingRegisters", IsRequired = true)]
    public ModbusRegion Region { get; init; }

    [CommandOption("address", 'a', Description = "Zero-based address within the region.", IsRequired = true)]
    public ushort Address { get; init; }

    [CommandOption("type", 't', Description =
        "Bool / Int16 / UInt16 / Int32 / UInt32 / Int64 / UInt64 / Float32 / Float64 / " +
        "BitInRegister / String / Bcd16 / Bcd32", IsRequired = true)]
    public ModbusDataType DataType { get; init; }

    [CommandOption("interval-ms", 'i', Description =
        "Publishing interval in milliseconds (default 1000). The PollGroupEngine enforces " +
        "a floor of ~250ms; values below it get rounded up.")]
    public int IntervalMs { get; init; } = 1000;

    [CommandOption("byte-order", Description =
        "BigEndian (default) or WordSwap.")]
    public ModbusByteOrder ByteOrder { get; init; } = ModbusByteOrder.BigEndian;

    public override async ValueTask ExecuteAsync(IConsole console)
    {
        ConfigureLogging();
        var ct = console.RegisterCancellationHandler();

        var tagName = ReadCommand.SynthesiseTagName(Region, Address, DataType);
        var tag = new ModbusTagDefinition(
            Name: tagName,
            Region: Region,
            Address: Address,
            DataType: DataType,
            Writable: false,
            ByteOrder: ByteOrder);
        var options = BuildOptions([tag]);

        await using var driver = new ModbusDriver(options, DriverInstanceId);
        ISubscriptionHandle? handle = null;
        try
        {
            await driver.InitializeAsync("{}", ct);

            // Route every data-change event to the CliFx console (not System.Console — the
            // analyzer flags it + IConsole is the testable abstraction).
            driver.OnDataChange += (_, e) =>
            {
                var line = $"[{DateTime.UtcNow:HH:mm:ss.fff}] " +
                    $"{e.FullReference} = {SnapshotFormatter.FormatValue(e.Snapshot.Value)} " +
                    $"({SnapshotFormatter.FormatStatus(e.Snapshot.StatusCode)})";
                console.Output.WriteLine(line);
            };

            handle = await driver.SubscribeAsync([tagName], TimeSpan.FromMilliseconds(IntervalMs), ct);

            await console.Output.WriteLineAsync(
                $"Subscribed to {tagName} @ {IntervalMs}ms. Ctrl+C to stop.");
            try
            {
                await Task.Delay(System.Threading.Timeout.InfiniteTimeSpan, ct);
            }
            catch (OperationCanceledException)
            {
                // Expected on Ctrl+C — fall through to the unsubscribe in finally.
            }
        }
        finally
        {
            if (handle is not null)
            {
                try { await driver.UnsubscribeAsync(handle, CancellationToken.None); }
                catch { /* teardown best-effort */ }
            }
            await driver.ShutdownAsync(CancellationToken.None);
        }
    }
}
