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.AbLegacy.Cli.Commands;

/// <summary>
///     Watch a PCCC file address via polled subscription until Ctrl+C. Mirrors the Modbus /
///     AB CIP subscribe shape — PollGroupEngine handles the tick loop.
/// </summary>
[Command("subscribe", Description = "Watch a PCCC file address via polled subscription until Ctrl+C.")]
public sealed class SubscribeCommand : AbLegacyCommandBase
{
    /// <summary>Gets or sets the PCCC file address to subscribe to.</summary>
    [CommandOption("address", 'a', Description = "PCCC file address — same format as `read`.", IsRequired = true)]
    public string Address { get; init; } = default!;

    /// <summary>Gets or sets the data type of the address.</summary>
    [CommandOption("type", 't', Description =
        "Bit / Int / Long / Float / AnalogInt / String / TimerElement / CounterElement / " +
        "ControlElement (default Int).")]
    public AbLegacyDataType DataType { get; init; } = AbLegacyDataType.Int;

    /// <summary>Gets or sets the polling interval in milliseconds.</summary>
    [CommandOption("interval-ms", 'i', Description =
        "Publishing interval in milliseconds (default 1000). PollGroupEngine floors " +
        "sub-250ms values.")]
    public int IntervalMs { get; init; } = 1000;

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

        var tagName = ReadCommand.SynthesiseTagName(Address, DataType);
        var tag = new AbLegacyTagDefinition(
            Name: tagName,
            DeviceHostAddress: Gateway,
            Address: Address,
            DataType: DataType,
            Writable: false);
        var options = BuildOptions([tag]);

        // Plain `var driver` (no `await using`): driver.DisposeAsync internally calls
        // ShutdownAsync, so combining `await using` with an explicit finally-shutdown
        // would tear the driver down twice. The explicit teardown is preferred because
        // it deliberately passes CancellationToken.None — `await using` would otherwise
        // happen on a cancelled `ct` path which can cut teardown short.
        var driver = new AbLegacyDriver(options, DriverInstanceId);
        ISubscriptionHandle? handle = null;
        // Serialise console writes from the poll-thread OnDataChange callback against
        // the command-thread "Subscribed to ..." line and against each other; the
        // PollGroupEngine raises change events on a background timer/loop thread.
        var consoleGate = new object();
        try
        {
            await driver.InitializeAsync("{}", ct);

            driver.OnDataChange += (_, e) =>
            {
                var line = $"[{DateTime.UtcNow:HH:mm:ss.fff}] " +
                    $"{e.FullReference} = {SnapshotFormatter.FormatValue(e.Snapshot.Value)} " +
                    $"({SnapshotFormatter.FormatStatus(e.Snapshot.StatusCode)})";
                lock (consoleGate)
                {
                    console.Output.WriteLine(line);
                }
            };

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

            lock (consoleGate)
            {
                console.Output.WriteLine(
                    $"Subscribed to {Address} @ {IntervalMs}ms. Ctrl+C to stop.");
            }
            try
            {
                await Task.Delay(System.Threading.Timeout.InfiniteTimeSpan, ct);
            }
            catch (OperationCanceledException)
            {
                // Expected on Ctrl+C.
            }
        }
        finally
        {
            if (handle is not null)
            {
                try { await driver.UnsubscribeAsync(handle, CancellationToken.None); }
                catch { /* teardown best-effort */ }
            }
            await driver.ShutdownAsync(CancellationToken.None);
            FlushLogging();
        }
    }
}
