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

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

/// <summary>
///     Watch a TwinCAT symbol until Ctrl+C. Native ADS notifications by default (TwinCAT
///     pushes on its own cycle); pass <c>--poll-only</c> to fall through to PollGroupEngine.
/// </summary>
[Command("subscribe", Description = "Watch a TwinCAT symbol via ADS notification or poll, until Ctrl+C.")]
public sealed class SubscribeCommand : TwinCATTagCommandBase
{
    /// <summary>Gets the TwinCAT symbol path to subscribe to.</summary>
    [CommandOption("symbol", 's', Description = "Symbol path — same format as `read`.", IsRequired = true)]
    public string SymbolPath { get; init; } = default!;

    /// <summary>Gets the TwinCAT data type of the symbol.</summary>
    [CommandOption("type", 't', Description =
        "Bool / SInt / USInt / Int / UInt / DInt / UDInt / LInt / ULInt / Real / LReal / " +
        "String / WString / Time / Date / DateTime / TimeOfDay (default DInt).")]
    public TwinCATDataType DataType { get; init; } = TwinCATDataType.DInt;

    /// <summary>Gets the publishing interval in milliseconds.</summary>
    [CommandOption("interval-ms", 'i', Description = "Publishing interval ms (default 1000).")]
    public int IntervalMs { get; init; } = 1000;

    /// <inheritdoc />
    protected override void Validate()
    {
        base.Validate();
        if (IntervalMs <= 0)
            throw new CommandException(
                $"--interval-ms must be greater than 0 (got {IntervalMs}).");
    }

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

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

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

            // Native ADS notifications fire OnDataChange from the Beckhoff.TwinCAT.Ads
            // notification callback thread — unlike the poll-mode path (which serialises on a
            // single PollGroupEngine loop), the native callback can interleave with the banner
            // write below and with subsequent change events if the PLC pushes faster than a
            // single console write completes. A TextWriter is not guaranteed thread-safe, so
            // we serialise every write through a lock to keep output clean for
            // screen-recorded bug-report timelines.
            var writeLock = new object();

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

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

            // Derive the banner mechanism from the actual subscription
            // handle the driver returned, not from --poll-only. The native ADS path tags its
            // handle with a "twincat-native-sub-*" DiagnosticId; anything else means we landed
            // on the shared PollGroupEngine. That way the line cannot disagree with what the
            // driver actually did (e.g. a future fallback inside SubscribeAsync).
            var mode = DescribeMechanism(handle);
            lock (writeLock)
            {
                console.Output.WriteLine(
                    $"Subscribed to {SymbolPath} @ {IntervalMs}ms ({mode}). 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();
        }
    }

    /// <summary>
    ///     Maps the returned subscription handle's <see cref="ISubscriptionHandle.DiagnosticId"/>
    ///     to the banner label. The TwinCAT driver tags native ADS subscriptions with
    ///     <c>twincat-native-sub-*</c> and the shared <c>PollGroupEngine</c> handle uses a
    ///     different format — anything else means we landed on the poll loop. Internal so the
    ///     test assembly can cover the mapping without spinning a real driver.
    /// </summary>
    /// <param name="handle">The subscription handle to describe.</param>
    /// <returns>A description of the subscription mechanism ("ADS notification" or "polling").</returns>
    internal static string DescribeMechanism(ISubscriptionHandle handle) =>
        handle.DiagnosticId.StartsWith("twincat-native-sub-", StringComparison.Ordinal)
            ? "ADS notification"
            : "polling";
}
