using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using ZB.MOM.WW.MxGateway.Contracts.Proto;
using ZB.MOM.WW.MxGateway.Worker.Sta;

namespace ZB.MOM.WW.MxGateway.Worker.MxAccess;

/// <summary>
/// Manages the runtime session between the worker and the MXAccess COM instance on an STA thread.
/// </summary>
public interface IWorkerRuntimeSession : IDisposable
{
    /// <summary>
    /// Starts the session, creates the MXAccess COM object, and returns ready metadata.
    /// </summary>
    /// <param name="sessionId">Identifier of the session.</param>
    /// <param name="workerProcessId">ID of the worker process.</param>
    /// <param name="cancellationToken">Token to cancel the asynchronous operation.</param>
    /// <returns>Asynchronous task returning worker readiness metadata.</returns>
    Task<WorkerReady> StartAsync(
        string sessionId,
        int workerProcessId,
        CancellationToken cancellationToken = default);

    /// <summary>
    /// Dispatches an STA command to the MXAccess runtime and returns the reply.
    /// </summary>
    /// <param name="command">STA command to execute on the STA thread.</param>
    /// <returns>Asynchronous task returning the command reply.</returns>
    Task<MxCommandReply> DispatchAsync(StaCommand command);

    /// <summary>
    /// Captures a heartbeat snapshot of the runtime state.
    /// </summary>
    /// <returns>The current heartbeat snapshot.</returns>
    WorkerRuntimeHeartbeatSnapshot CaptureHeartbeat();

    /// <summary>
    /// Drains up to the specified number of pending events from the queue.
    /// </summary>
    /// <param name="maxEvents">Maximum number of events to drain.</param>
    /// <returns>List of drained events.</returns>
    IReadOnlyList<WorkerEvent> DrainEvents(uint maxEvents);

    /// <summary>
    /// Drains pending events bounded by both a count cap and a byte budget, so a caller building a
    /// single reply frame never removes an event it cannot ship.
    /// </summary>
    /// <remarks>
    ///     Declared as a second method rather than a default interface method: the worker targets
    ///     .NET Framework 4.8, which has no runtime support for default interface members.
    /// </remarks>
    /// <param name="maxEvents">Maximum number of events to drain; 0 means "no count limit".</param>
    /// <param name="maxTotalBytes">Byte budget for the drained events' estimated serialized size.</param>
    /// <returns>The drained events and the truncation facts describing what stayed queued.</returns>
    WorkerEventDrainResult DrainEvents(uint maxEvents, int maxTotalBytes);

    /// <summary>
    ///     Waits until the outbound event queue has something for the caller to look at (an
    ///     enqueued event or a recorded fault), the fallback timeout elapses, or the token is
    ///     cancelled. Lets a drain loop be signal-driven instead of polling.
    /// </summary>
    /// <remarks>
    ///     Declared on the interface because the pipe session only ever sees an
    ///     <see cref="IWorkerRuntimeSession"/>, never the queue behind it; .NET Framework 4.8 has
    ///     no default interface members, so every implementation supplies it. The wait's outcome is
    ///     not surfaced: the caller re-drains and re-checks <see cref="DrainFault"/> after every
    ///     wait, because the signal is coalesced and the timeout is a ceiling, not a poll period.
    ///     <para>
    ///         Precondition: <b>at most one waiter</b>. The implementation's wake signal carries a
    ///         single permit, which is sufficient only because a session has exactly one event
    ///         drain loop; a second concurrent waiter would degrade to the fallback timeout.
    ///     </para>
    /// </remarks>
    /// <param name="timeout">Maximum time to wait before the wait completes unsignalled.</param>
    /// <param name="cancellationToken">Token cancelling the wait.</param>
    /// <returns>A task that completes when the queue is signalled or the timeout elapses.</returns>
    Task WaitForEventsAsync(TimeSpan timeout, CancellationToken cancellationToken);

    /// <summary>
    /// Drains a pending fault from the queue, if any.
    /// </summary>
    /// <returns>The pending fault, or <see langword="null"/> if none is queued.</returns>
    WorkerFault? DrainFault();

    /// <summary>
    /// Cancels a pending command by correlation ID.
    /// </summary>
    /// <param name="correlationId">Correlation ID of the command to cancel.</param>
    /// <returns>True if the command was found and cancelled; otherwise, false.</returns>
    bool CancelCommand(string correlationId);

    /// <summary>
    /// Requests a graceful shutdown of the session.
    /// </summary>
    void RequestShutdown();

    /// <summary>
    /// Shuts down the session gracefully within the specified timeout.
    /// </summary>
    /// <param name="timeout">Maximum time to allow for graceful shutdown.</param>
    /// <param name="cancellationToken">Token to cancel the asynchronous operation.</param>
    /// <returns>Asynchronous task returning the shutdown result.</returns>
    Task<MxAccessShutdownResult> ShutdownGracefullyAsync(
        TimeSpan timeout,
        CancellationToken cancellationToken = default);
}
