namespace ZB.MOM.WW.OtOpcUa.Driver.AbCip;

/// <summary>
///     Thin wire-layer abstraction over a single CIP tag. The driver holds one instance per
///     <c>(device, tag path)</c> pair; the default implementation delegates to
///     <see cref="LibplctagTagRuntime"/>. Tests swap in a fake via
///     <see cref="IAbCipTagFactory"/> so the driver's read / write / status-mapping logic can
///     be exercised without a running PLC or the native libplctag binary.
/// </summary>
public interface IAbCipTagRuntime : IDisposable
{
    /// <summary>Create the underlying native tag (equivalent to libplctag's <c>plc_tag_create</c>).</summary>
    /// <param name="cancellationToken">Cancellation token.</param>
    /// <returns>A task that represents the asynchronous operation.</returns>
    Task InitializeAsync(CancellationToken cancellationToken);

    /// <summary>Issue a read; on completion the local buffer holds the current PLC value.</summary>
    /// <param name="cancellationToken">Cancellation token.</param>
    /// <returns>A task that represents the asynchronous operation.</returns>
    Task ReadAsync(CancellationToken cancellationToken);

    /// <summary>Flush the local buffer to the PLC.</summary>
    /// <param name="cancellationToken">Cancellation token.</param>
    /// <returns>A task that represents the asynchronous operation.</returns>
    Task WriteAsync(CancellationToken cancellationToken);

    /// <summary>
    ///     Raw libplctag status code — mapped to an OPC UA StatusCode via
    ///     <see cref="AbCipStatusMapper.MapLibplctagStatus(int)"/>. Zero on success, negative on error.
    /// </summary>
    /// <returns>The raw libplctag status code (zero on success, negative on error).</returns>
    int GetStatus();

    /// <summary>
    ///     Decode the local buffer into a boxed .NET value per the tag's configured type.
    ///     <paramref name="bitIndex"/> is non-null only for BOOL-within-DINT tags captured in
    ///     the <c>.N</c> syntax at parse time.
    /// </summary>
    /// <param name="type">CIP data type to decode.</param>
    /// <param name="bitIndex">Bit index for BOOL-within-DINT extraction, or null.</param>
    /// <returns>The decoded value, or <c>null</c> if the type is unsupported.</returns>
    object? DecodeValue(AbCipDataType type, int? bitIndex);

    /// <summary>
    ///     Decode a value at an arbitrary byte offset in the local buffer. Whole-UDT reads
    ///     perform one <see cref="ReadAsync"/> on the parent UDT tag then
    ///     call this per declared member with its computed offset, avoiding one libplctag
    ///     round-trip per member. Implementations that do not support offset-aware decoding
    ///     may fall back to <see cref="DecodeValue"/> when <paramref name="offset"/> is zero;
    ///     offsets greater than zero against an unsupporting runtime should return <c>null</c>
    ///     so the planner can skip grouping.
    /// </summary>
    /// <param name="type">CIP data type to decode.</param>
    /// <param name="offset">Byte offset in the buffer.</param>
    /// <param name="bitIndex">Bit index for BOOL-within-DINT extraction, or null.</param>
    /// <returns>The decoded value, or <c>null</c> if the type is unsupported.</returns>
    object? DecodeValueAt(AbCipDataType type, int offset, int? bitIndex);

    /// <summary>
    ///     Phase 4c — decode the local buffer into an element-typed CLR array of
    ///     <paramref name="count"/> elements, boxed as <see cref="object"/> (e.g.
    ///     <c>int[]</c>, <c>float[]</c>, <c>bool[]</c>, <c>string[]</c>). The driver calls this
    ///     for a 1-D array tag after a single array <see cref="ReadAsync"/> (libplctag pulls all
    ///     elements in one transaction via its <c>elem_count</c>). Each element is decoded at its
    ///     byte stride within the buffer; scalar (count &lt;= 1) reads stay on
    ///     <see cref="DecodeValue"/>.
    /// </summary>
    /// <param name="type">CIP element data type to decode.</param>
    /// <param name="count">Number of array elements to decode.</param>
    /// <returns>A boxed element-typed CLR array, or <c>null</c> if the type is unsupported.</returns>
    object? DecodeArray(AbCipDataType type, int count);

    /// <summary>
    ///     Encode <paramref name="value"/> into the local buffer per the tag's type. Callers
    ///     pair this with <see cref="WriteAsync"/>.
    /// </summary>
    /// <param name="type">CIP data type to encode.</param>
    /// <param name="bitIndex">Bit index for BOOL-within-DINT insertion, or null.</param>
    /// <param name="value">Value to encode.</param>
    void EncodeValue(AbCipDataType type, int? bitIndex, object? value);
}

/// <summary>
///     Factory for per-tag runtime handles. Instantiated once per driver, consumed per
///     <c>(device, tag path)</c> pair at the first read/write.
/// </summary>
public interface IAbCipTagFactory
{
    /// <summary>Creates a tag runtime handle from the specified creation parameters.</summary>
    /// <param name="createParams">Parameters needed to create the tag runtime.</param>
    /// <returns>The created tag runtime handle.</returns>
    IAbCipTagRuntime Create(AbCipTagCreateParams createParams);
}

/// <summary>Everything libplctag needs to materialise a tag handle.</summary>
/// <param name="Gateway">Gateway IP / hostname parsed from <see cref="AbCipHostAddress.Gateway"/>.</param>
/// <param name="Port">EtherNet/IP TCP port — default 44818.</param>
/// <param name="CipPath">CIP route path, e.g. <c>1,0</c>. Empty for Micro800.</param>
/// <param name="LibplctagPlcAttribute">libplctag <c>plc=...</c> attribute, per family profile.</param>
/// <param name="TagName">Logix symbolic tag name as emitted by <see cref="AbCipTagPath.ToLibplctagName"/>.</param>
/// <param name="Timeout">libplctag operation timeout (applies to Initialize / Read / Write).</param>
/// <param name="AllowPacking">CIP request-packing flag — combines the per-device override (if
///     any) with the family profile's <c>SupportsRequestPacking</c>. Forwarded to the libplctag
///     <c>Tag.AllowPacking</c> property.</param>
/// <param name="ConnectionSize">Forward Open ConnectionSize — combines the per-device override
///     (if any) with the family profile's <c>DefaultConnectionSize</c>. libplctag 1.5.2 has no
///     direct <c>ConnectionSize</c> property; the value is plumbed for forward-compat with future
///     wrappers / a custom tag-attribute path.</param>
/// <param name="ElementCount">Phase 4c — libplctag <c>elem_count</c>. Forwarded to the
///     libplctag <c>Tag.ElementCount</c> property so a 1-D array tag pulls all elements in one
///     CIP transaction. Defaults to 1 (scalar); the driver sets it from the tag definition's
///     element count for an <c>isArray</c> tag — including a 1-element array.</param>
/// <param name="IsArray">Review I-1 — the EXPLICIT array signal threaded from the tag definition so
///     a 1-element array (<see cref="ElementCount"/> 1) is still read as an array, not a scalar.</param>
public sealed record AbCipTagCreateParams(
    string Gateway,
    int Port,
    string CipPath,
    string LibplctagPlcAttribute,
    string TagName,
    TimeSpan Timeout,
    bool AllowPacking = true,
    int ConnectionSize = 4002,
    int ElementCount = 1,
    bool IsArray = false);
