using ZB.MOM.WW.MxGateway.Client;
using ZB.MOM.WW.MxGateway.Contracts.Proto;
// Use the generated nested status enum for the SetBufferedUpdateInterval reply check.

namespace ZB.MOM.WW.OtOpcUa.Driver.Galaxy.Runtime;

/// <summary>
///     Production <see cref="IGalaxySubscriber"/> over a connected
///     <see cref="GalaxyMxSession"/>. Forwards SubscribeBulk / UnsubscribeBulk to the
///     gateway and streams MxEvents via the gw's bidirectional events RPC.
/// </summary>
/// <remarks>
///     PR 6.3 wired the per-call <c>buffered_update_interval_ms</c> through
///     <see cref="SubscribeBulkAsync"/>. The gw's contract is session-level
///     (<c>SetBufferedUpdateInterval</c> applies to all buffered subscriptions on the
///     server handle), so we cache the last-applied value and skip redundant calls.
/// </remarks>
public sealed class GatewayGalaxySubscriber : IGalaxySubscriber
{
    private readonly GalaxyMxSession _session;
    private readonly Lock _intervalLock = new();
    private int _lastAppliedIntervalMs = -1; // -1 = never applied; 0 = explicit "use gw default"

    /// <summary>Initializes a new instance of GatewayGalaxySubscriber.</summary>
    /// <param name="session">The Galaxy MX session to use for subscription operations.</param>
    public GatewayGalaxySubscriber(GalaxyMxSession session)
    {
        _session = session ?? throw new ArgumentNullException(nameof(session));
    }

    /// <summary>Subscribes to a bulk list of Galaxy references with optional buffered update interval.</summary>
    /// <param name="fullReferences">The full Galaxy tag references to subscribe to.</param>
    /// <param name="bufferedUpdateIntervalMs">The buffered update interval in milliseconds.</param>
    /// <param name="cancellationToken">The cancellation token.</param>
    /// <returns>A task that returns a list of subscribe results.</returns>
    public async Task<IReadOnlyList<SubscribeResult>> SubscribeBulkAsync(
        IReadOnlyList<string> fullReferences, int bufferedUpdateIntervalMs, CancellationToken cancellationToken)
    {
        var session = _session.Session
            ?? throw new InvalidOperationException(
                "GalaxyMxSession is not connected. Call ConnectAsync before subscribing.");
        var serverHandle = _session.ServerHandle;

        // The gw's SubscribeBulk RPC doesn't carry a per-call interval — buffered cadence
        // is session-level, set via SetBufferedUpdateInterval. Apply it before the
        // SubscribeBulk so the very first events on the new handles publish at the
        // requested cadence. Skip when the last-applied value already matches.
        if (bufferedUpdateIntervalMs > 0)
        {
            await EnsureSessionIntervalAsync(session, serverHandle, bufferedUpdateIntervalMs, cancellationToken)
                .ConfigureAwait(false);
        }

        return await session.SubscribeBulkAsync(serverHandle, fullReferences, cancellationToken)
            .ConfigureAwait(false);
    }

    /// <summary>
    ///     Apply the gateway's session-level <c>SetBufferedUpdateInterval</c> command. The
    ///     gw's contract is "for this server handle, every buffered subscription publishes
    ///     at this cadence" — there's no per-handle granularity, so we cache the last
    ///     applied value and skip redundant calls.
    /// </summary>
    private async Task EnsureSessionIntervalAsync(
        ZB.MOM.WW.MxGateway.Client.MxGatewaySession session, int serverHandle, int intervalMs, CancellationToken cancellationToken)
    {
        lock (_intervalLock)
        {
            if (_lastAppliedIntervalMs == intervalMs) return;
        }

        var reply = await session.InvokeAsync(
            new MxCommandRequest
            {
                SessionId = session.SessionId,
                ClientCorrelationId = Guid.NewGuid().ToString("N"),
                Command = new MxCommand
                {
                    Kind = MxCommandKind.SetBufferedUpdateInterval,
                    SetBufferedUpdateInterval = new SetBufferedUpdateIntervalCommand
                    {
                        ServerHandle = serverHandle,
                        UpdateIntervalMilliseconds = intervalMs,
                    },
                },
            },
            cancellationToken).ConfigureAwait(false);

        if (reply.ProtocolStatus?.Code is not (ProtocolStatusCode.Ok or ProtocolStatusCode.MxaccessFailure))
        {
            // Don't throw on a soft failure — the SubscribeBulk will still succeed at the
            // gw's default cadence, which is functional just not the requested cadence.
            // The trace span (PR 6.1) plus the warning here gives ops the signal.
            return;
        }

        lock (_intervalLock)
        {
            _lastAppliedIntervalMs = intervalMs;
        }
    }

    /// <summary>Unsubscribes from a bulk list of item handles.</summary>
    /// <param name="itemHandles">The item handles to unsubscribe from.</param>
    /// <param name="cancellationToken">The cancellation token.</param>
    /// <returns>A task representing the unsubscribe operation.</returns>
    public async Task UnsubscribeBulkAsync(IReadOnlyList<int> itemHandles, CancellationToken cancellationToken)
    {
        if (itemHandles.Count == 0) return;

        var session = _session.Session
            ?? throw new InvalidOperationException(
                "GalaxyMxSession is not connected. UnsubscribeBulk called after disconnect.");
        var serverHandle = _session.ServerHandle;

        await session.UnsubscribeBulkAsync(serverHandle, itemHandles, cancellationToken)
            .ConfigureAwait(false);
    }

    /// <summary>Streams Galaxy MX events asynchronously.</summary>
    /// <param name="cancellationToken">The cancellation token.</param>
    /// <returns>An async enumerable of MX events.</returns>
    public IAsyncEnumerable<MxEvent> StreamEventsAsync(CancellationToken cancellationToken)
    {
        var session = _session.Session
            ?? throw new InvalidOperationException(
                "GalaxyMxSession is not connected. StreamEventsAsync called before ConnectAsync.");
        return session.StreamEventsAsync(afterWorkerSequence: 0, cancellationToken);
    }
}
